Search code examples
next.jssentry

Capture 400's and 500's under Axios interceptors for sentry


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?


Solution

  • 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);
          });