How to stop code execution after a 401 response in Axios
Bilal Haidar
Posted on October 5, 2023
Let's dive deeper into how the Axios interceptor works and how to ensure that code execution stops after a 401 response.
Axios Interceptor Overview:
Axios interceptors are functions that Axios allows you to define globally for all requests or responses. These functions can be used to modify requests or responses, handle errors, or perform other tasks before or after the HTTP request is made.The Problem:
In your case, you want to redirect the user to the login page when a 401 (Unauthorized) response is received. However, you also want to make sure that no further code executes after the redirection.Stopping Execution:
In JavaScript, promises are used to handle asynchronous operations, like HTTP requests. When a promise is rejected, it typically moves to the nearestcatch
block to handle the error. However, if you want to stop execution completely, you can throw an exception inside thecatch
block.-
Solution with Explanation:
In the Axios interceptor, when you usereturn Promise.reject('Unauthorized');
, you're essentially throwing an exception with the message 'Unauthorized.' This stops the promise chain and ensures that any subsequent.then()
blocks are skipped. In your case, this is important because you don't want any further code execution after the redirection. Here's the flow:- Axios interceptor detects a 401 response.
- It redirects the user to the login page using
router.push('/login')
. - Immediately after, it throws an exception by returning
Promise.reject('Unauthorized');
. - The promise chain is halted, and any code that would have run after the Axios request (e.g., additional
.then()
blocks) won't execute.
Handling the Exception:
In your application, you should have error handling mechanisms in place to catch exceptions like 'Unauthorized' and handle them appropriately. For example, you might want to show an error message to the user if something goes wrong during the redirection process.
Here's a more detailed code example that shows how you might handle the exception:
axios.interceptors.response.use(
(response) => {
return response;
},
(error) => {
if (error.response && error.response.status === 401) {
// Use router.push() to navigate to the login screen
router.push('/login'); // Adjust the route as needed
// Throw an exception to stop further execution
return Promise.reject('Unauthorized');
}
// Handle other errors here
return Promise.reject(error);
}
);
// Example usage of the Axios request:
axios.get('/api/some-data')
.then((response) => {
// Handle a successful response
console.log('Data received:', response.data);
})
.catch((error) => {
if (error === 'Unauthorized') {
// Handle the unauthorized error (e.g., show an error message)
console.log('Unauthorized. Please log in.');
} else {
// Handle other errors here
console.error('An error occurred:', error);
}
});
With this approach, you have fine-grained control over how to handle different types of errors, including the 'Unauthorized' error caused by the interceptor.
Posted on October 5, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.