Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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;
@cosecantt

This comment has been minimized.

Copy link

@cosecantt cosecantt commented Aug 11, 2018

Please change:

{ handleErrors: false } to { errorHandle: false }
@saqueib

This comment has been minimized.

Copy link
Owner Author

@saqueib saqueib commented Sep 13, 2018

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

@pmochine

This comment has been minimized.

Copy link

@pmochine pmochine commented Sep 29, 2018

Thanks man! Just was looking for this.

@josegus

This comment has been minimized.

Copy link

@josegus 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

This comment has been minimized.

Copy link

@chrise86 chrise86 commented Nov 29, 2018

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

@hcivelek

This comment has been minimized.

Copy link

@hcivelek hcivelek commented Dec 22, 2018

@josegus me either. any solution?

@hcivelek

This comment has been minimized.

Copy link

@hcivelek hcivelek commented Dec 22, 2018

I found it! axios/axios#960

@ridaamirini

This comment has been minimized.

Copy link

@ridaamirini ridaamirini commented Feb 18, 2019

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

@alectogeek

This comment has been minimized.

Copy link

@alectogeek alectogeek commented Jun 20, 2019

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

@gautam-patadiya

This comment has been minimized.

Copy link

@gautam-patadiya gautam-patadiya commented Jun 26, 2019

Thanks a lot. Working Good

@mikelito859

This comment has been minimized.

Copy link

@mikelito859 mikelito859 commented Aug 21, 2019

Thanks

@mkaarthick

This comment has been minimized.

Copy link

@mkaarthick mkaarthick commented Oct 2, 2019

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

This comment has been minimized.

Copy link

@Godofbrowser Godofbrowser commented Nov 16, 2019

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

@devinrhode2

This comment has been minimized.

Copy link

@devinrhode2 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