React

了解 Sentry 的 React SDK 以及它如何自动报告应用程序中的错误和异常。

Sentry 的 React SDK 启用了错误和异常的自动报告。该 SDK 是围绕 @sentry/browser 的一个包装,并添加了与 React 相关的功能。@sentry/browser 中的所有方法都可以从 @sentry/react 导入。

除了捕获错误,您还可以通过启用追踪来监控多个服务或应用程序之间的交互。您还可以通过会话重放更快地找到错误或性能问题的根本原因,观看用户会话的视频回放。

选择您希望安装的 Sentry 功能(除错误监控外),以获取相应的安装和配置说明。

Sentry 通过在应用程序运行时使用 SDK 来捕获数据。

Copied
npm install @sentry/react --save

Sentry 支持多个版本的 React Router。要了解如何配置它们,请阅读React Router 集成文档。

Sentry 应该尽可能早地在你的应用程序中初始化。我们建议将 Sentry 初始化代码放在自己的文件中,并将其作为第一个导入包含在应用程序入口文件中,如下例所示:

instrument.js
Copied
import { useEffect } from "react";
import * as Sentry from "@sentry/react";
import {
  createRoutesFromChildren,
  matchRoutes,
  useLocation,
  useNavigationType,
} from "react-router-dom";

Sentry.init({
  dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",
  integrations: [
    // See docs for support of different versions of variation of react router
    // https://docs.sentry.io/platforms/javascript/guides/react/configuration/integrations/react-router/
    Sentry.reactRouterV6BrowserTracingIntegration({
      useEffect,
      useLocation,
      useNavigationType,
      createRoutesFromChildren,
      matchRoutes,
    }),
    Sentry.replayIntegration(),
  ],

  // Set tracesSampleRate to 1.0 to capture 100%
  // of transactions for tracing.
  // Learn more at
  // https://docs.sentry.io/platforms/javascript/configuration/options/#traces-sample-rate
  tracesSampleRate: 1.0,

  // Set `tracePropagationTargets` to control for which URLs trace propagation should be enabled
  tracePropagationTargets: [/^\//, /^https:\/\/yourserver\.io\/api/],

  // Capture Replay for 10% of all sessions,
  // plus for 100% of sessions with an error
  // Learn more at
  // https://docs.sentry.io/platforms/javascript/session-replay/configuration/#general-integration-configuration
  replaysSessionSampleRate: 0.1,
  replaysOnErrorSampleRate: 1.0,
});

将 Sentry 初始化文件作为第一个导入语句包含:

Copied
// Sentry initialization should be imported first!
import "./instrument";
import App from "./App";
import { createRoot } from "react-dom/client";

const container = document.getElementById(“app”);
const root = createRoot(container);
root.render(<App />);

完成此操作后,所有未处理的异常将被 Sentry 自动捕获。

从 React 19 开始,react-dom 中的 createRoothydrateRoot 方法将暴露错误钩子,用于自动捕获错误。要自定义特定错误钩子中错误的处理方式,请使用 Sentry.reactErrorHandler 函数。

Copied
import { createRoot } from "react-dom/client";

const container = document.getElementById(“app”);
const root = createRoot(container, {
  // Callback called when an error is thrown and not caught by an ErrorBoundary.
  onUncaughtError: Sentry.reactErrorHandler((error, errorInfo) => {
    console.warn('Uncaught error', error, errorInfo.componentStack);
  }),
  // Callback called when React catches an error in an ErrorBoundary.
  onCaughtError: Sentry.reactErrorHandler(),
  // Callback called when React automatically recovers from errors.
  onRecoverableError: Sentry.reactErrorHandler(),
});
root.render();

这些钩子适用于所有挂载到传递给 createRoot/hydrateRoot 的容器的 React 组件。为了更精确地控制错误处理,我们建议在你的应用程序中添加一个 ErrorBoundary 组件。

如果你使用的是 React 16 或更高版本,可以使用 错误边界组件 自动将组件树内的 JavaScript 错误发送到 Sentry,并设置备用 UI。

React Router 集成旨在与我们的跟踪包配合使用。了解更多关于 React Router 集成 的设置。

要将 Sentry 应用于 Redux,请了解 Redux 集成 及其选项。

根据您项目的设置方式,Sentry 错误中的堆栈跟踪可能不会显示为您的实际代码。

要解决此问题,请将源映射上传到 Sentry。最简单的方法是使用 Sentry 向导:

Copied
npx @sentry/wizard@latest -i sourcemaps

向导将引导您完成以下步骤:

  • 登录 Sentry 并选择一个项目
  • 安装必要的 Sentry 包
  • 配置您的构建工具以生成和上传源映射
  • 配置您的 CI 以上传源映射

有关源映射的更多信息或更多上传选项,请参阅我们的 源映射文档

此代码片段包含一个有意的错误,因此您可以立即测试设置是否正常工作。

Copied
<button
  type="button"
  onClick={() => {
    throw new Error("Sentry Test Error");
  }}
>
  Break the world
</button>;

了解更多关于手动捕获错误或消息的信息,请参阅我们的使用文档

要查看和解决记录的错误,请登录 sentry.io 并选择您的项目。单击错误标题将打开一个页面,您可以在其中查看详细信息并将其标记为已解决。