Normalize the errors messages with Axios interceptors and Element UI

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) { return; }, 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 $message from ElementUI it can show a fancy error into page.

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