网站搜索

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


我正在开发一个 Next.js 应用程序,并使用 Sentry 进行错误跟踪。我已经成功配置 Sentry 来捕获我 try/catch 块中的错误,但我在全局层面(在我的 sentry.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 {};

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

答案#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)