在React应用中实现Sentry自定义传输时遇到的问题
排查Sentry自定义传输请求成功但无数据的问题
以下是几个核心排查方向和修正方案:
1. 请求体格式错误(最可能的原因)
你当前的代码把Sentry提供的request.body嵌套在了{ body: req.body }中传递给axios,这会导致Sentry收到的是一个嵌套结构的JSON(比如{"body":"{...}"}),而非预期的事件数据格式。Sentry虽然会返回200,但无法解析这种无效的payload,自然不会在控制台显示数据。
修正方式:直接将request.body作为axios的POST数据传递,不要嵌套:
axios.post(fullUrl, request.body, { headers: { 'Content-Type': 'application/json', }, })
2. URL拼接错误
Sentry自定义传输的options.url是基础域名,而具体的上报路径在request.path中(比如/api/xxx/store/)。你直接使用options.url作为请求地址,会导致请求发送到错误的endpoint。
修正方式:拼接完整的上报URL:
const fullUrl = `${options.url}${request.path}`;
3. 响应状态判断逻辑有误
你当前无论响应状态如何都返回status: 'success',如果Sentry返回200但实际是无效请求(比如payload格式错误),Sentry不会处理事件,但你的传输层会告诉Sentry“发送成功”,导致不会重试。
修正方式:根据HTTP状态码判断是否成功:
return sendMyCustomRequest().then((response) => { const isSuccess = response.status >= 200 && response.status < 300; return { headers: { 'x-sentry-rate-limits': response.headers['X-Sentry-Rate-Limits'], 'retry-after': response.headers['Retry-After'], }, statusCode: response.status ?? 500, status: isSuccess ? 'success' : 'failure', }; }).catch((error) => { return { statusCode: error.response?.status ?? 500, status: 'failure', }; });
4. 遗漏必要的请求头
Sentry上报需要特定的请求头(比如X-Sentry-Auth),这些头信息已经包含在request.headers中,需要传递给axios。
修正方式:在请求中添加request.headers:
axios.post(fullUrl, request.body, { headers: { 'Content-Type': 'application/json', ...request.headers, }, })
完整修正后的代码示例
function makeMyCustomTransport(options) { function makeRequest(request) { // 拼接完整的Sentry上报地址 const fullUrl = `${options.url}${request.path}`; function sendMyCustomRequest() { return axios.post(fullUrl, request.body, { headers: { 'Content-Type': 'application/json', ...request.headers, }, }); } return sendMyCustomRequest().then((response) => { const isSuccess = response.status >= 200 && response.status < 300; return { headers: { 'x-sentry-rate-limits': response.headers['X-Sentry-Rate-Limits'], 'retry-after': response.headers['Retry-After'], }, statusCode: response.status ?? 500, status: isSuccess ? 'success' : 'failure', }; }).catch((error) => { return { statusCode: error.response?.status ?? 500, status: 'failure', }; }); } return createTransport(options, makeRequest); } Sentry.init({ dsn: '.....', integrations: [new Sentry.Replay(), new Debug()], tracesSampleRate: 1.0, replaysSessionSampleRate: 0.1, replaysOnErrorSampleRate: 1.0, debug: true, transport: makeMyCustomTransport, })
额外排查点
- 检查UWP应用的网络权限:确保Package.appxmanifest中开启了对Sentry域名的网络访问权限
- 查看Sentry Debug日志:开启
debug: true后,控制台会输出Sentry的传输细节,可确认事件是否被正确发送 - 验证DSN正确性:确保DSN中的项目ID、公钥等信息无误
内容的提问来源于stack exchange,提问作者Saleh
相关产品推荐
相关产品推荐

