name: sentry-error-capturing description: 当捕获和报告错误到Sentry时使用,添加上下文或处理异常。涵盖错误边界、上下文丰富和指纹识别。 allowed-tools:
- 读取
- 写入
- 编辑
- Bash
- Grep
- Glob
Sentry - 错误捕获与上下文
捕获错误并用上下文丰富它们,以便更好地调试。
捕获错误
手动错误捕获
import * as Sentry from "@sentry/browser";
try {
riskyOperation();
} catch (error) {
Sentry.captureException(error);
}
捕获额外上下文
Sentry.captureException(error, {
tags: {
section: "checkout",
feature: "payment",
},
extra: {
orderId: order.id,
cartItems: cart.items.length,
},
level: "error",
});
捕获消息
Sentry.captureMessage("用户超出速率限制", {
level: "warning",
tags: { userId: user.id },
});
添加上下文
用户上下文
Sentry.setUser({
id: user.id,
email: user.email,
username: user.username,
ip_address: "{{auto}}",
});
// 登出时清除
Sentry.setUser(null);
标签
// 全局标签
Sentry.setTag("app.version", "1.2.3");
Sentry.setTag("tenant", customer.tenantId);
// 每个事件的标签
Sentry.captureException(error, {
tags: { operation: "database_query" },
});
额外数据
Sentry.setExtra("orderDetails", {
items: order.items,
total: order.total,
});
上下文对象
Sentry.setContext("order", {
id: order.id,
status: order.status,
items: order.items.length,
});
Sentry.setContext("customer", {
plan: customer.plan,
region: customer.region,
});
面包屑
自动面包屑
// 大多数集成自动添加面包屑
// 控制台、fetch、XHR、DOM事件、导航
手动面包屑
Sentry.addBreadcrumb({
category: "auth",
message: "用户登录",
level: "info",
data: {
userId: user.id,
method: "oauth",
},
});
配置面包屑
Sentry.init({
beforeBreadcrumb(breadcrumb, hint) {
// 过滤或修改面包屑
if (breadcrumb.category === "console") {
return null; // 不捕获控制台日志
}
return breadcrumb;
},
maxBreadcrumbs: 50,
});
错误边界(React)
import * as Sentry from "@sentry/react";
// 基本错误边界
const App = () => (
<Sentry.ErrorBoundary fallback={<ErrorPage />}>
<YourApp />
</Sentry.ErrorBoundary>
);
// 使用自定义回退和onError
<Sentry.ErrorBoundary
fallback={({ error, resetError }) => (
<div>
<p>出错:{error.message}</p>
<button onClick={resetError}>重试</button>
</div>
)}
onError={(error, componentStack) => {
console.error("被Sentry边界捕获:", error);
}}
beforeCapture={(scope) => {
scope.setTag("location", "checkout");
}}
>
<CheckoutFlow />
</Sentry.ErrorBoundary>
指纹识别
自定义分组
Sentry.captureException(error, {
fingerprint: ["{{ default }}", user.id],
});
覆盖默认分组
Sentry.init({
beforeSend(event) {
if (event.exception?.values?.[0]?.type === "ChunkLoadError") {
event.fingerprint = ["chunk-load-error"];
}
return event;
},
});
范围
配置范围
Sentry.configureScope((scope) => {
scope.setUser({ id: user.id });
scope.setTag("theme", "dark");
scope.setLevel("warning");
});
使用范围(隔离)
Sentry.withScope((scope) => {
scope.setTag("operation", "batch_import");
scope.setExtra("batchSize", items.length);
Sentry.captureException(error);
});
// 标签/额外数据仅在此范围内应用
最佳实践
- 登录时设置用户上下文,登出时清除
- 添加相关业务上下文(如订单ID、租户等)
- 使用标签用于可筛选、可索引的数据
- 使用额外数据用于详细调试信息
- 在功能边界实现错误边界
- 使用指纹识别分组相关错误
- 为关键用户操作添加面包屑