- Published on
How to Handle HTTP Error Using Interceptor in Axios
- Authors
- Name
- Ashik Nesin
- @AshikNesin
Interceptor in axios can be attached to a request or a response. And they're executed before or after every request and response globally.
One of the most common use case is handling Unauthorized request.
Let’s see how to handle those errors globally.
Handling error message in Axios using Interceptor
In our example, we're going to listen for 401/403 HTTP Code in response and redirect them to login page.
Depedency
npm i axios
Snippet
const axios = require('axios');
// import axios from "axios";
axios.interceptors.response.use(
res => res,
err => {
// Any HTTP Code which is not 2xx will be considered as error
const statusCode = err.response.status;
if (statusCode === 401 || statusCode === 403) {
window.location = '/login';
}
throw err;
}
);