Skip to content

Instantly share code, notes, and snippets.

@hardevine
Forked from saqueib/errorHandler.js
Created March 14, 2020 05:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hardevine/3e3f53dbb2f46490eda454f213cf7795 to your computer and use it in GitHub Desktop.
Save hardevine/3e3f53dbb2f46490eda454f213cf7795 to your computer and use it in GitHub Desktop.
Global error handling using axios interceptor for http calls http://www.qcode.in/api-error-handling-in-vue-with-axios

How to use it

I am assuming you have a Laravel app with axios installed.

  1. Run npm install izitoast --save to pull the iziToast
  2. Create a resources/assets/js/services folder and place toast.js and errorHandler.js in it.
  3. Now open the resources/assets/js/bootstrap.js and add following:
...
window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

require('./services/errorHandler');
  1. Thats it, now you should be seeing toast notification on request fail.

Turn on gloabl error handling for specific call

You can turn on the global error handling for a specific request by passing {errorHandle: false} as config in axios call.

axios.get('/user/1', {errorHandle: false}).then((response) => {
    console.log('Everything is awesome.');
}).catch((error) => {
    // handle this error here
    console.warn('Not good man :(');
})
import axios from 'axios'
import toast from './toast'
function errorResponseHandler(error) {
// check for errorHandle config
if( error.config.hasOwnProperty('errorHandle') && error.config.errorHandle === false ) {
return Promise.reject(error);
}
// if has response show the error
if (error.response) {
toast.error(error.response.data.message);
}
}
// apply interceptor on response
axios.interceptors.response.use(
response => response,
errorResponseHandler
);
export default errorResponseHandler;
import 'izitoast/dist/css/iziToast.min.css'
import iZtoast from 'izitoast'
const toast = {
error: (message, title = 'Error') => {
return iZtoast.error({
title: title,
message: message,
position: 'bottomCenter'
});
},
success: (message, title = 'Success') => {
return iZtoast.success({
title: title,
message: message,
position: 'bottomCenter'
});
}
};
export default toast;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment