在 Axios 拦截器下捕获 400 和 500 的哨兵

vis*_*zky 9 sentry next.js

使用 Axios 拦截器通过显示错误弹出窗口以通用方式处理 400 和 500。通常,当由于 JS 错误而渲染自定义 _error.js 页面时,会触发 Sentry 调用。如何在sentry中记录API调用错误?

小智 15

您可以使用 axios 拦截器或将其写入 axios 调用本身的 catch() 中。

拦截器

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

Axios 呼叫

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

Run Code Online (Sandbox Code Playgroud)