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

如何在不使用context.reportLocation的情况下上报Google Error Reporting错误

Google Cloud Error Reporting API 无context.reportLocation上报示例

正确的message格式要求

  • 第一行必须为[异常类型]: [错误消息]格式(例如ValidationError: Missing required field)
  • 换行后跟随标准堆栈跟踪,每一行需以 at开头(四个空格+at),对应函数调用位置

JavaScript 示例代码

1. 使用官方 SDK (@google-cloud/error-reporting)

const {ErrorReporting} = require('@google-cloud/error-reporting');

// 初始化错误上报客户端
const errorReporter = new ErrorReporting({
  projectId: '你的项目ID',
  keyFilename: '你的密钥文件路径'
});

// 模拟从请求负载获取的字符串格式错误信息
const payloadError = {
  errorType: 'ValidationError',
  errorMsg: 'Missing required field: user_id',
  stackLines: [
    'validatePayload (/app/routes/users.js:45:12)',
    'createUser (/app/routes/users.js:20:5)',
    'processTicksAndRejections (node:internal/process/task_queues:96:5)'
  ]
};

// 构造符合API要求的message字符串
const formattedMessage = [
  `${payloadError.errorType}: ${payloadError.errorMsg}`,
  ...payloadError.stackLines.map(line => `    at ${line}`)
].join('\n');

// 上报错误(不传入context.reportLocation)
errorReporter.report(formattedMessage, {
  serviceContext: {
    service: 'user-service',
    version: 'v1.0.0'
  }
}).catch(err => {
  console.error('上报失败:', err);
});

2. 直接调用 REST API

const projectId = '你的项目ID';
const apiKey = '你的API密钥';
const reportUrl = `https://clouderrorreporting.googleapis.com/v1beta1/projects/${projectId}/events:report?key=${apiKey}`;

// 模拟请求负载中的错误信息
const payloadError = {
  errorType: 'TypeError',
  errorMsg: 'Invalid input format',
  stackLines: [
    'parseRequestPayload (/app/middleware/parser.js:30:8)',
    'handleRequest (/app/routes/api.js:15:3)',
    'processTicksAndRejections (node:internal/process/task_queues:96:5)'
  ]
};

// 构造合规的message
const formattedMessage = [
  `${payloadError.errorType}: ${payloadError.errorMsg}`,
  ...payloadError.stackLines.map(line => `    at ${line}`)
].join('\n');

// 发送上报请求
fetch(reportUrl, {
  method: 'POST',
  headers: {'Content-Type': 'application/json'},
  body: JSON.stringify({
    message: formattedMessage,
    serviceContext: {
      service: 'api-gateway',
      version: 'v2.1.0'
    }
    // 禁止添加context.reportLocation字段
  })
})
.then(res => res.json())
.then(data => console.log('上报成功:', data))
.catch(err => console.error('上报失败:', err));

关键注意事项

  • 必须保留[异常类型]: [错误消息]的头部行,否则API无法识别为有效异常
  • 堆栈行的 at前缀不能省略,这是API识别堆栈的关键标识
  • 绝对不要传入context.reportLocation字段,否则会触发参数冲突错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 20:01:02