You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js v13中自定义_error页面结合Sentry捕获异常失效求助

在Next.js 13.1中配置自定义Error页面结合Sentry捕获404及所有异常

一、确认Sentry初始化配置正确性

检查根目录下的sentry.client.config.js和sentry.server.config.js是否完成正确初始化:

  • 客户端配置需包含路由追踪集成,确保捕获前端路由相关错误:
    import * as Sentry from '@sentry/nextjs';
    
    Sentry.init({
      dsn: '你的Sentry DSN',
      tracesSampleRate: 1.0,
      integrations: [
        new Sentry.BrowserTracing({
          routingInstrumentation: Sentry.nextjsRouterInstrumentation(
            React.useEffect,
            false
          ),
        }),
      ],
    });
    
  • 服务端配置需确保在Next.js启动前完成初始化:
    import * as Sentry from '@sentry/nextjs';
    
    Sentry.init({
      dsn: '你的Sentry DSN',
      tracesSampleRate: 1.0,
    });
    

二、修正自定义_error.tsx的实现(Pages Router)

Next.js 13.1的Pages Router中,_error.tsx需要手动在服务端和客户端捕获错误并上报Sentry,以下是两种实现方式:

类组件实现

import NextErrorComponent from 'next/error';
import * as Sentry from '@sentry/nextjs';
import { Component, ErrorInfo, ReactNode } from 'react';

interface ErrorComponentProps {
  statusCode?: number;
  children?: ReactNode;
}

class ErrorComponent extends Component<ErrorComponentProps> {
  // 捕获服务端渲染时的错误
  static getInitialProps({ res, err }: any) {
    const statusCode = res?.statusCode || err?.statusCode || 500;
    if (err) {
      Sentry.captureException(err);
    }
    return { statusCode };
  }

  // 捕获客户端渲染时的错误
  componentDidCatch(error: Error, errorInfo: ErrorInfo) {
    Sentry.captureException(error, { contexts: { react: errorInfo } });
  }

  render() {
    return <NextErrorComponent statusCode={this.props.statusCode} />;
  }
}

export default ErrorComponent;

函数组件实现(结合React ErrorBoundary)

import NextErrorComponent from 'next/error';
import * as Sentry from '@sentry/nextjs';
import { ErrorBoundary, FallbackProps } from 'react-error-boundary';

const ErrorFallback = ({ error }: FallbackProps) => {
  // 上报客户端错误
  Sentry.captureException(error);
  const statusCode = (error as any)?.statusCode || 500;
  return <NextErrorComponent statusCode={statusCode} />;
};

const ErrorComponent = ({ statusCode }: { statusCode?: number }) => {
  return (
    <ErrorBoundary FallbackComponent={ErrorFallback}>
      <NextErrorComponent statusCode={statusCode} />
    </ErrorBoundary>
  );
};

// 捕获服务端渲染时的错误
ErrorComponent.getInitialProps = async ({ res, err }: any) => {
  const statusCode = res?.statusCode || err?.statusCode || 500;
  if (err) {
    Sentry.captureException(err);
  }
  return { statusCode };
};

export default ErrorComponent;

三、配置next.config.js确保Sentry插件生效

检查next.config.js中的Sentry插件配置,确保未禁用错误捕获:

const { withSentryConfig } = require('@sentry/nextjs');

const nextConfig = {
  // 你的其他Next.js配置项
};

module.exports = withSentryConfig(nextConfig, {
  silent: true,
  org: '你的Sentry组织名',
  project: '你的Sentry项目名',
  widenClientFileUpload: true,
  transpileClientSDK: true,
  tunnelRoute: '/monitoring',
  hideSourceMaps: true,
  disableLogger: true,
});

四、全局捕获404错误(无需页面级return { notFound: true })

创建自定义404.tsx页面,在服务端和客户端统一上报404错误到Sentry:

import * as Sentry from '@sentry/nextjs';
import { useEffect } from 'react';

const Custom404 = () => {
  // 客户端渲染时上报404
  useEffect(() => {
    const notFoundError = new Error('404: Page Not Found');
    (notFoundError as any).statusCode = 404;
    Sentry.captureException(notFoundError);
  }, []);

  return (
    <div className="container">
      <h1>404 - 页面不存在</h1>
    </div>
  );
};

// 服务端渲染时上报404
Custom404.getInitialProps = async ({ res }) => {
  if (res) {
    res.statusCode = 404;
    const notFoundError = new Error('404: Page Not Found');
    (notFoundError as any).statusCode = 404;
    Sentry.captureException(notFoundError);
  }
  return {};
};

export default Custom404;

五、常见问题排查

  • 依赖版本兼容:确保@sentry/nextjs版本为7.x(如7.40.0+),与Next.js 13.1兼容。
  • 开发环境验证:Next.js开发模式会显示内置错误页面,需构建生产包测试,或在next.config.js中添加productionBrowserSourceMaps: true。
  • 避免局部ErrorBoundary拦截:页面级的ErrorBoundary会阻止错误冒泡到全局_error.tsx,需检查是否存在此类组件。

内容的提问来源于stack exchange,提问作者Prokop Simek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 08:25:15