如何使用 Next.js 在 Sentry 中捕获特定的 React 警告?

How to Capture Specific React Warnings in Sentry with Next.js?

提问人:Luke 提问时间:11/15/2023 更新时间:11/15/2023 访问量:29

问:

我正在开发一个Next.js应用程序并使用 Sentry 进行错误跟踪。我已成功将 Sentry 配置为捕获块中的错误,但我在全局级别、文件中捕获特定错误和警告方面面临挑战。我想捕获的示例警告是:try/catchsentry.client.config.ts

Warning: React has detected a change in the order of Hooks called by CandidateTable. This will lead to bugs and errors if not fixed. For more information, read the Rules of Hooks: https://reactjs.org/link/rules-of-hooks

sentry.client.config.ts

import * as Sentry from "@sentry/nextjs";

const dsn = process.env.NEXT_PUBLIC_SENTRY_DSN;

Sentry.init({
  dsn,
  tracesSampleRate: 1,
  debug: false,
  replaysOnErrorSampleRate: 1.0,
  replaysSessionSampleRate: 0.1,
  integrations: [
    new Sentry.Replay({
      maskAllText: true,
      blockAllMedia: true,
    }),
  ],
});

if (typeof window !== "undefined") {
  // Attach error event listener
  window.addEventListener("error", (event) => {
    Sentry.captureException(event.error);
  });

  // Attach unhandledrejection event listener
  window.addEventListener("unhandledrejection", (event) => {
    Sentry.captureException(event.reason);
  });

  // Override console.error
  const originalConsoleError = console.error;
  console.error = (...args: any[]) => {
    Sentry.captureException(new Error(args.join(" ")));
    originalConsoleError.apply(console, args);
  };

  // Override console.warn
  const originalConsoleWarn = console.warn;
  console.warn = function (...args) {
    // Check if the warning message is related to React's hooks order
    if (typeof args[0] === "string" && args[0].includes("Rules of Hooks")) {
      Sentry.captureMessage(`React Hook Order Warning: ${args.join(" ")}`, "warning");
    }
    originalConsoleWarn.apply(console, args);
  };
}

export {};

我知道我的项目工作之间的联系,因为我可以从示例页面发送他们的示例错误。

reactjs 打字稿 next.js 哨兵

评论


答:

1赞 Luca Forstner 11/15/2023 #1

Next.js将在内部捕获 React 错误,并且不会将它们传递给任何全局错误处理程序。您可以设置一个自定义页面,通过该页面将错误传递到该页面。_error

有关自定义错误页面的信息:https://nextjs.org/docs/pages/building-your-application/routing/custom-error

使用 Sentry 仪器会是什么样子:

import * as Sentry from "@sentry/nextjs";
import type { NextPage } from "next";
import type { ErrorProps } from "next/error";
import Error from "next/error";

const CustomErrorComponent: NextPage<ErrorProps> = (props) => {
  return <Error statusCode={props.statusCode} />;
};

CustomErrorComponent.getInitialProps = async (contextData) => {
  // In case this is running in a serverless function, await this in order to give Sentry
  // time to send the error before the lambda exits
  await Sentry.captureUnderscoreErrorException(contextData);

  // This will contain the status code of the response
  return Error.getInitialProps(contextData);
};

export default CustomErrorComponent;

(文档可以在这里找到:https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup/#report-react-component-render-errors)