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

如何在@Sentry/react中捕获失败POST请求的请求体?

解决方案:默认将POST请求体附加到Sentry失败请求异常中

Sentry 默认不会自动捕获 POST 请求体(避免泄露敏感数据),但你可以通过以下两种方式实现默认追踪:

方法1:自定义Sentry Fetch集成

在初始化Sentry时,修改Fetch集成的配置,让它在生成请求面包屑或异常事件时包含请求体:

import { init } from "@sentry/react";
import { Integrations } from "@sentry/tracing";

init({
  dsn: "你的DSN地址",
  integrations: [
    new Integrations.Fetch({
      beforeBreadcrumb: (breadcrumb, hint) => {
        // 仅处理POST请求的面包屑
        if (breadcrumb.category === "fetch" && breadcrumb.data?.method === "POST") {
          const request = hint?.fetchData?.request;
          if (request?.body) {
            // 解析JSON格式请求体,非JSON格式可调整逻辑
            try {
              breadcrumb.data.body = JSON.parse(request.body);
            } catch (e) {
              breadcrumb.data.body = "无法解析的非JSON请求体";
            }
          }
        }
        return breadcrumb;
      },
    }),
  ],
  addGlobalEventProcessor: (event) => {
    // 给异常事件附加请求体上下文
    const reqCtx = event.contexts?.request;
    if (reqCtx?.method === "POST") {
      // 可结合全局缓存的请求体数据补充到事件中
    }
    return event;
  },
  tracesSampleRate: 1.0,
});

方法2:全局拦截fetch请求

通过重写全局fetch方法,在请求失败时自动将请求体附加到Sentry异常中:

// 在项目入口文件(如index.js)中添加
const originalFetch = window.fetch;

window.fetch = async (...args) => {
  const [url, options] = args;
  let requestBody = null;

  // 记录POST请求的请求体
  if (options?.method === "POST" && options?.body) {
    try {
      // 克隆请求体避免原请求流被消耗
      requestBody = typeof options.body === "string" 
        ? JSON.parse(options.body) 
        : await options.body.clone().text();
    } catch (e) {
      requestBody = "无法解析的请求体";
    }
  }

  try {
    const response = await originalFetch(...args);
    // 捕获非2xx状态码的失败请求
    if (!response.ok) {
      const error = new Error(`请求失败: ${response.status} ${response.statusText}`);
      Sentry.withScope(scope => {
        scope.setExtra("requestBody", requestBody);
        scope.setExtra("requestUrl", url);
        scope.setExtra("requestMethod", options?.method);
        Sentry.captureException(error);
      });
    }
    return response;
  } catch (err) {
    // 捕获网络类异常并附加请求体
    Sentry.withScope(scope => {
      scope.setExtra("requestBody", requestBody);
      scope.setExtra("requestUrl", url);
      scope.setExtra("requestMethod", options?.method);
      Sentry.captureException(err);
    });
    throw err;
  }
};

注意事项

  • 敏感数据过滤:请求体可能包含密码、token等敏感信息,务必在添加前过滤这类字段。
  • 多格式适配:如果请求体是FormData、Blob等格式,需要调整解析逻辑,避免报错。
  • 版本兼容:以上代码针对@sentry/react ^7.16.0版本验证有效,不同版本API可能存在差异。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 16:45:45