You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js集成Sentry后无法捕获网络请求错误求助

捕获Next.js中Sentry的网络请求错误

Sentry的@sentry/nextjs默认不会自动捕获所有HTTP状态码类的网络错误,需要通过以下方式配置实现:

客户端捕获方案

1. 启用Sentry Http集成(推荐)

在客户端的Sentry初始化代码中添加Http集成,它会自动监听fetch和XMLHttpRequest的请求错误:

import * as Sentry from '@sentry/nextjs';
import { Http } from '@sentry/integrations';
import { CaptureConsole } from '@sentry/integrations';

Sentry.init({
  dsn: '***',
  integrations: [
    new CaptureConsole(),
    new Http({
      // 自定义需要捕获的状态码,默认捕获400及以上
      failedRequestStatusCodes: [400, 401, 403, 404, 500, 502, 503],
      // 开启失败请求捕获
      captureFailedRequests: true,
    }),
  ],
  tracesSampleRate: 1.0,
});

如果未安装@sentry/integrations,先执行安装命令:

npm install @sentry/integrations

2. 自定义请求拦截(适用于封装过的请求库)

如果项目使用自定义fetch或Axios等请求库,可手动在请求失败时上报:

// 封装fetch示例
const customFetch = async (url, options) => {
  try {
    const response = await fetch(url, options);
    if (!response.ok) {
      const httpError = new Error(`HTTP错误: ${response.status} ${response.statusText}`);
      // 上报错误并附带请求详情
      Sentry.captureException(httpError, {
        extra: {
          url,
          method: options?.method || 'GET',
          statusCode: response.status,
        },
      });
    }
    return response;
  } catch (error) {
    Sentry.captureException(error);
    throw error;
  }
};

// 替换全局fetch(可选)
window.fetch = customFetch;

服务端捕获方案

对于服务端发起的请求(如getServerSideProps、API路由内的请求),需要手动拦截上报:

import * as Sentry from '@sentry/nextjs';

export async function getServerSideProps() {
  try {
    const res = await fetch('https://your-api-endpoint.com/data');
    if (!res.ok) {
      const serverError = new Error(`服务端请求错误: ${res.status} ${res.statusText}`);
      Sentry.captureException(serverError, {
        extra: {
          url: 'https://your-api-endpoint.com/data',
          statusCode: res.status,
        },
      });
      throw serverError;
    }
    const data = await res.json();
    return { props: { data } };
  } catch (err) {
    Sentry.captureException(err);
    return { props: {} };
  }
}

注意事项

  • Next.js的API路由中,若错误被正确抛出,Sentry会自动捕获,但HTTP状态码错误需手动判断上报
  • 使用Axios时,可通过响应拦截器统一处理:在response interceptor中判断response.status,不符合预期时调用Sentry.captureException

内容的提问来源于stack exchange,提问作者Aditya Shrivastava

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 22:05:26