7

Using Axios interceptors to handle the 400's and 500's in a generic manner by showing an Error Popup. Usually, Sentry calls are triggered when the custom _error.js page is rendered due to a JS error. How do I log the API call errors in sentry?

visizky
  • 701
  • 1
  • 8
  • 27

2 Answers2

14

You can either use an axios interceptor or write it in the catch() of your axios call itself.

Interceptor

axios.interceptors.response.use(
  (response: AxiosResponse) => response,
  (error: AxiosError) => {
    Sentry.captureException(error);
    return Promise.reject(error);
  },
);

Axios Call

axios({
      url,
      method,
      ...
    })
      .then(async (response: AxiosResponse) => {
        resolve(response.data);
      })
      .catch(async (error: AxiosError) => {
        Sentry.captureException(error);
        reject(error);
      });

Janith
  • 156
  • 2
  • 3
3

I think you have to follow the docs here: https://axios-http.com/docs/handling_errors

axios.interceptors.response.use(
  (response: AxiosResponse) => response,
  (error: AxiosError) => {
    if (error.response) {
      // The request was made and the server responded with a status code
      // that falls out of the range of 2xx
      Sentry.captureException(error.response.data);
    } 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.log(error.request);
    } else {
      // Something happened in setting up the request that triggered an Error
      Sentry.captureException(error.message);
    }
    Sentry.captureException(error);
    return Promise.reject(error);
  },
);
therealcobb
  • 147
  • 7