This is a short example of how to catch all Axios HTTP requests, responses, and errors. Catching is implemented with the Axios feature called interceptors. It's possible to catch all requests before they are sent and modify them. Also, responses and errors can be caught globally. For example, interceptors are useful when you want to modify request headers before a request is sent or you are implementing some kind of global error handling system.
Of course, for real use case, it might be too general to handle all requests and responses in the same way. That’s why we will also have a configuration option for each HTTP requests to disable global handling.
In the demo, I have used VanillaToasts library to show a notification when a HTTP request is done.
Start by installing Axios by the instructions.
Create a new instance and add any global config options you might need to use.
Add isHandlerEnabled function which will check if the global handler should be used or not. Here it's also possible to implement additional custom logic. For example, enabling the handler only for the certain HTTP response codes.
return config.hasOwnProperty('handlerEnabled') && !config.handlerEnabled ?
Now we are later able to disable handler for an individual HTTP call if we want to.
One common use case for a request handler is to modify or add new HTTP headers. For example, an authentication token could be injected into all requests.
And now every request made by Axios uses the handlers we have defined.