Skip to content

Instantly share code, notes, and snippets.

@saqueib
Last active June 9, 2022 06:42
Show Gist options
  • Star 55 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save saqueib/a495af17d7c0e2fd5c2316b0822ebac3 to your computer and use it in GitHub Desktop.
Save saqueib/a495af17d7c0e2fd5c2316b0822ebac3 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 off gloabl error handling for specific call

You can turn off 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;
@saqueib
Copy link
Author

saqueib commented Sep 13, 2018

@cosecantt thanks for pointing out, silly typo fixed it 😠

@pmochine
Copy link

Thanks man! Just was looking for this.

@josegus
Copy link

josegus commented Oct 21, 2018

Please, excuse if i'm wrong, but whenever i change to { handleError: true } in my component axios call, i still getting whatever my .then() callback does. I mean, i can see the toast message but the process go throught .then() callback anywhere. I think this is because the incerceptor still need to return something, and if (error.response) { toast.. } is returning nothing

@chrise86
Copy link

@josegus also facing this issue - did you come up with a solution?

@hcivelek
Copy link

@josegus me either. any solution?

@hcivelek
Copy link

I found it! axios/axios#960

@ridaamirini
Copy link

It is better to add return Promise.reject(error); at the end.

@alectogeek
Copy link

Typo in "Turn on gloabl error handling for specific call"

@gautam-patadiya
Copy link

Thanks a lot. Working Good

@mikelito859
Copy link

Thanks

@mkaarthick
Copy link

This doesn't seem to work with axios 0.19.x. Any idea how to pass the errorHandle flag in the latest version of axios?

@Godofbrowser
Copy link

This makes sense... You can also try this approach I use personally guys medium article

@devinrhode2
Copy link

devinrhode2 commented Sep 10, 2020

I am using something like this

    // From axios github readme:
    if (error.response) {
      // The request was made and the server responded with a status code
      // that falls out of the range of 2xx
      console.error(error.response.data);
      // toast.error(error.response.data.message); // TODO setup toast notification here
      console.error(error.response.status);
      console.error(error.response.headers);
    } else if (error.request) {
      // The request was made but no response was received
      // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
      // http.ClientRequest in node.js
      console.error(error.request);
    } else {
      // Something happened in setting up the request that triggered an Error
      console.error("Error", error.message);
    }
    console.error("full error object", error);

    // modified from https://gist.github.com/saqueib/a495af17d7c0e2fd5c2316b0822ebac3
    // you can individually handle an error for any ajax call by doing this:
    // axios
    //   .get("/user/1", { handleErrorLocally: true })
    //   .then((response) => console.log("Everything is awesome."))
    //   .catch((error) => {
    //     // handle this error here
    //     console.warn("Not good man :(");
    //   });
    if (
      error.config.hasOwnProperty("handleErrorLocally") &&
      error.config.handleErrorLocally === true
    ) {
      console.error(
        "error.config has handleErrorLocally property, returning error object"
      );
      return Promise.reject(error);
    } else {
      // Throwing in this interceptor may be incorrect behavior in some circumstances,
      // please feel free to change this.
      throw new Error("request failed");
    }

Although I think @Godofbrowser's medium article is pretty great. Typescript is great, but I'm not yet that committed to typescript enough to use interface and class ComposedAjaxError implements ComposedError` although I feel that day is coming soon, I'm holding out for optional static typing to become standardized in ES

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment