捕获错误和事件

学习如何使用 SDK 手动捕获错误和其他事件。

Sentry 的 SDK 会集成到您的运行时环境中,自动报告错误、未捕获的异常和未处理的拒绝,以及其他类型的错误,具体取决于平台。

关键术语:

  • 事件 是向 Sentry 发送数据的一个实例。通常,这些数据是错误或异常。
  • 问题 是一组相似的事件。
  • 向 Sentry 报告事件的过程称为 捕获。当事件被捕获时,它会被发送到 Sentry。

最常见的捕获形式是捕获错误。可以捕获的内容因平台而异。一般来说,如果某事物看起来像一个异常,就可以被捕获。对于某些 SDK,您可以省略 captureException 的参数,Sentry 将尝试捕获当前异常。手动报告错误或消息给 Sentry 也非常有用。

在捕获事件时,您还可以记录导致该事件的面包屑(breadcrumbs)。面包屑与事件不同:它们不会在 Sentry 中创建事件,而是会被缓冲,直到下一个事件被发送。更多关于面包屑的信息,请参阅我们的 面包屑文档

By including and configuring Sentry, our React SDK automatically attaches global handlers to capture uncaught exceptions and unhandled promise rejections, as described in the official ECMAScript 6 standard. You can disable this default behavior by changing the onunhandledrejection option to false in your GlobalHandlers integration and manually hook into each event handler, then call Sentry.captureException or Sentry.captureMessage directly.

You can pass an Error object to captureException() to get it captured as an event. It's also possible to pass non-Error objects and strings, but be aware that the resulting events in Sentry may be missing a stack trace.

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

try {
  aFunctionThatMightFail();
} catch (err) {
  Sentry.captureException(err);
}

Sentry calls like captureException or captureMessage are side effects, so they should be wrapped in a useEffect hook to avoid triggering them on every render.

Copied
import * as Sentry from "@sentry/react";
import { useEffect } from "react";

function App() {
  const [info, error] = useQuery("/api/info");
  useEffect(() => {
    if (error) {
      Sentry.captureException(error);
    }
  }, [error]);

  // ...
}

另一个常见的操作是捕获纯文本消息。消息是应发送到 Sentry 的文本信息。通常,我们的 SDK 不会自动捕获消息,但您可以手动捕获它们。

消息会在您的问题流中显示为问题,消息本身作为问题名称。

Copied
Sentry.captureMessage("Something went wrong");

// optionally specify the severity level:
// "fatal" | "error" | "warning" | "log" | "debug" | "info" (default)
Sentry.captureMessage("Something went wrong", "warning");