How to handle HTTP errors with Element UI and Axios.

Sometimes I want to find an easy way to handle HTTP errors. Using Axios interceptors, we handle requests and response before the then or catch.

I will create a Vue EventBus instance to communicate my interceptor with the app and emit an event when some error happened.

const EventBus = new Vue(); 
axios.interceptors.response.use( function(response) { 
function(error) { 
EventBus.$emit('error', 'sorry try more later'); 
return Promise.reject(error); 

Into the Vue instance, the eventBus is registered to listen to the error event and be handled, using the $message from ElementUI it can show a fancy error into the page.

let app = new Vue({ 
el: "# app", 
created() { EventBus.$on("error", showerror); }); 
methods: { 
Showerror: (msg) { this.$message({ message: msg, type: "warning" } } 
} });


Originally published at on October 28, 2018.