Introduction

Axios interceptors in Vue.js provide a powerful way to handle global responses, including error handling, authentication checks, and more. By using interceptors, you can centralize the response handling logic and apply it to all HTTP requests made with Axios. In this guide, we'll explore how to implement global response handling with Axios interceptors in Vue.js and provide sample code to demonstrate the process.


Sample Code

Let's create a Vue.js application and configure Axios interceptors for global response handling:


<div id="app">
<button @click="fetchData">Fetch Data</button>
<p v-if="errorMessage">{{ errorMessage }}</p>
const app = new Vue({
el: '#app',
data: {
errorMessage: null,
},
methods: {
fetchData() {
axios.get('https://api.example.com/data')
.then(response => {
// Process and use the response data here
this.errorMessage = null;
})
.catch(error => {
this.errorMessage = 'An error occurred while fetching data.';
});
},
},
});
// Configure Axios interceptors
axios.interceptors.response.use(
response => response,
error => {
if (error.response) {
// Handle HTTP error responses here
// For example, check for unauthorized (401) or other error statuses
} else {
// Handle network or other errors here
app.errorMessage = 'Network error: Unable to reach the server.';
}
return Promise.reject(error);
}
);

In this code:

  • We create a Vue component that contains a button to fetch data and a paragraph to display error messages.
  • The `fetchData` method uses Axios to make an HTTP GET request to an external API.
  • We handle HTTP and network errors in the `fetchData` method by displaying appropriate error messages.
  • Additionally, we configure Axios interceptors to handle global response and error handling. The interceptors check for HTTP error responses and network errors and provide custom error messages accordingly.