sentry-error-capturing

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Sentry - Error Capturing & Context

Sentry - 错误捕获与上下文

Capture errors and enrich them with context for better debugging.
捕获错误并为其添加上下文,以优化调试体验。

Capturing Errors

错误捕获

Manual Error Capture

手动捕获错误

typescript
import * as Sentry from "@sentry/browser";

try {
  riskyOperation();
} catch (error) {
  Sentry.captureException(error);
}
typescript
import * as Sentry from "@sentry/browser";

try {
  riskyOperation();
} catch (error) {
  Sentry.captureException(error);
}

Capture with Extra Context

附带额外上下文的捕获

typescript
Sentry.captureException(error, {
  tags: {
    section: "checkout",
    feature: "payment",
  },
  extra: {
    orderId: order.id,
    cartItems: cart.items.length,
  },
  level: "error",
});
typescript
Sentry.captureException(error, {
  tags: {
    section: "checkout",
    feature: "payment",
  },
  extra: {
    orderId: order.id,
    cartItems: cart.items.length,
  },
  level: "error",
});

Capture Messages

捕获消息

typescript
Sentry.captureMessage("User exceeded rate limit", {
  level: "warning",
  tags: { userId: user.id },
});
typescript
Sentry.captureMessage("User exceeded rate limit", {
  level: "warning",
  tags: { userId: user.id },
});

Adding Context

添加上下文

User Context

用户上下文

typescript
Sentry.setUser({
  id: user.id,
  email: user.email,
  username: user.username,
  ip_address: "{{auto}}",
});

// Clear on logout
Sentry.setUser(null);
typescript
Sentry.setUser({
  id: user.id,
  email: user.email,
  username: user.username,
  ip_address: "{{auto}}",
});

// 登出时清除
Sentry.setUser(null);

Tags

标签

typescript
// Global tags
Sentry.setTag("app.version", "1.2.3");
Sentry.setTag("tenant", customer.tenantId);

// Per-event tags
Sentry.captureException(error, {
  tags: { operation: "database_query" },
});
typescript
// 全局标签
Sentry.setTag("app.version", "1.2.3");
Sentry.setTag("tenant", customer.tenantId);

// 单事件标签
Sentry.captureException(error, {
  tags: { operation: "database_query" },
});

Extra Data

额外数据

typescript
Sentry.setExtra("orderDetails", {
  items: order.items,
  total: order.total,
});
typescript
Sentry.setExtra("orderDetails", {
  items: order.items,
  total: order.total,
});

Context Objects

上下文对象

typescript
Sentry.setContext("order", {
  id: order.id,
  status: order.status,
  items: order.items.length,
});

Sentry.setContext("customer", {
  plan: customer.plan,
  region: customer.region,
});
typescript
Sentry.setContext("order", {
  id: order.id,
  status: order.status,
  items: order.items.length,
});

Sentry.setContext("customer", {
  plan: customer.plan,
  region: customer.region,
});

Breadcrumbs

面包屑

Automatic Breadcrumbs

自动生成面包屑

typescript
// Most integrations add breadcrumbs automatically
// Console, fetch, XHR, DOM events, navigation
typescript
// 大多数集成会自动添加面包屑
// 控制台、fetch、XHR、DOM事件、导航相关

Manual Breadcrumbs

手动添加面包屑

typescript
Sentry.addBreadcrumb({
  category: "auth",
  message: "User logged in",
  level: "info",
  data: {
    userId: user.id,
    method: "oauth",
  },
});
typescript
Sentry.addBreadcrumb({
  category: "auth",
  message: "User logged in",
  level: "info",
  data: {
    userId: user.id,
    method: "oauth",
  },
});

Configure Breadcrumbs

配置面包屑

typescript
Sentry.init({
  beforeBreadcrumb(breadcrumb, hint) {
    // Filter or modify breadcrumbs
    if (breadcrumb.category === "console") {
      return null; // Don't capture console logs
    }
    return breadcrumb;
  },
  maxBreadcrumbs: 50,
});
typescript
Sentry.init({
  beforeBreadcrumb(breadcrumb, hint) {
    // 过滤或修改面包屑
    if (breadcrumb.category === "console") {
      return null; // 不捕获控制台日志
    }
    return breadcrumb;
  },
  maxBreadcrumbs: 50,
});

Error Boundaries (React)

错误边界(React)

tsx
import * as Sentry from "@sentry/react";

// Basic error boundary
const App = () => (
  <Sentry.ErrorBoundary fallback={<ErrorPage />}>
    <YourApp />
  </Sentry.ErrorBoundary>
);

// With custom fallback and onError
<Sentry.ErrorBoundary
  fallback={({ error, resetError }) => (
    <div>
      <p>Something went wrong: {error.message}</p>
      <button onClick={resetError}>Try again</button>
    </div>
  )}
  onError={(error, componentStack) => {
    console.error("Caught by Sentry boundary:", error);
  }}
  beforeCapture={(scope) => {
    scope.setTag("location", "checkout");
  }}
>
  <CheckoutFlow />
</Sentry.ErrorBoundary>
tsx
import * as Sentry from "@sentry/react";

// 基础错误边界
const App = () => (
  <Sentry.ErrorBoundary fallback={<ErrorPage />}>
    <YourApp />
  </Sentry.ErrorBoundary>
);

// 自定义回退组件与错误处理
<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>

Fingerprinting

错误指纹识别

Custom Grouping

自定义分组

typescript
Sentry.captureException(error, {
  fingerprint: ["{{ default }}", user.id],
});
typescript
Sentry.captureException(error, {
  fingerprint: ["{{ default }}", user.id],
});

Override Default Grouping

覆盖默认分组

typescript
Sentry.init({
  beforeSend(event) {
    if (event.exception?.values?.[0]?.type === "ChunkLoadError") {
      event.fingerprint = ["chunk-load-error"];
    }
    return event;
  },
});
typescript
Sentry.init({
  beforeSend(event) {
    if (event.exception?.values?.[0]?.type === "ChunkLoadError") {
      event.fingerprint = ["chunk-load-error"];
    }
    return event;
  },
});

Scopes

作用域(Scopes)

Configure Scope

配置作用域

typescript
Sentry.configureScope((scope) => {
  scope.setUser({ id: user.id });
  scope.setTag("theme", "dark");
  scope.setLevel("warning");
});
typescript
Sentry.configureScope((scope) => {
  scope.setUser({ id: user.id });
  scope.setTag("theme", "dark");
  scope.setLevel("warning");
});

With Scope (Isolated)

独立作用域

typescript
Sentry.withScope((scope) => {
  scope.setTag("operation", "batch_import");
  scope.setExtra("batchSize", items.length);
  Sentry.captureException(error);
});
// Tags/extra only apply within this scope
typescript
Sentry.withScope((scope) => {
  scope.setTag("operation", "batch_import");
  scope.setExtra("batchSize", items.length);
  Sentry.captureException(error);
});
// 标签/额外数据仅在该作用域内生效

Best Practices

最佳实践

  1. Set user context on login, clear on logout
  2. Add relevant business context (order ID, tenant, etc.)
  3. Use tags for filterable, indexable data
  4. Use extra for detailed debugging data
  5. Implement error boundaries at feature boundaries
  6. Use fingerprinting to group related errors
  7. Add breadcrumbs for critical user actions
  1. 登录时设置用户上下文,登出时清除
  2. 添加相关业务上下文(如订单ID、租户信息等)
  3. 使用标签存储可过滤、可索引的数据
  4. 使用额外字段存储详细调试数据
  5. 在功能边界处实现错误边界
  6. 使用指纹识别对相关错误进行分组
  7. 为关键用户操作添加面包屑