错误处理
本文档解释了如何处理开发、服务器端和客户端错误。
处理开发环境中的错误
当你的 Next.js 应用在开发阶段发生运行时错误时,你会遇到一个覆盖层。它是一个覆盖网页的模态框。它只在使用 next dev
通过 pnpm dev
、npm run dev
、yarn dev
或 bun dev
运行开发服务器时可见,并且不会在生产环境中显示。修复错误将自动关闭覆盖层。
这是一个覆盖层的示例
处理服务器错误
Next.js 默认提供一个静态 500 页面来处理应用中发生的服务器端错误。你也可以通过创建一个 pages/500.js
文件来自定义此页面。
在你的应用中使用 500 页面不会向应用用户显示具体的错误信息。
你还可以使用 404 页面 来处理特定的运行时错误,例如 文件未找到
。
处理客户端错误
React 错误边界 是一种优雅地处理客户端 JavaScript 错误的方式,以便应用程序的其他部分继续工作。除了防止页面崩溃外,它还允许你提供自定义的回退组件,甚至记录错误信息。
要为你的 Next.js 应用程序使用错误边界,你必须创建一个类组件 ErrorBoundary
,并将 pages/_app.js
文件中的 Component
属性包裹起来。此组件将负责
- 在抛出错误后渲染回退 UI
- 提供一种重置应用程序状态的方法
- 记录错误信息
你可以通过扩展 React.Component
来创建一个 ErrorBoundary
类组件。例如
class ErrorBoundary extends React.Component {
constructor(props) {
super(props)
// Define a state variable to track whether is an error or not
this.state = { hasError: false }
}
static getDerivedStateFromError(error) {
// Update state so the next render will show the fallback UI
return { hasError: true }
}
componentDidCatch(error, errorInfo) {
// You can use your own error logging service here
console.log({ error, errorInfo })
}
render() {
// Check if the error is thrown
if (this.state.hasError) {
// You can render any custom fallback UI
return (
<div>
<h2>Oops, there is an error!</h2>
<button
type="button"
onClick={() => this.setState({ hasError: false })}
>
Try again?
</button>
</div>
)
}
// Return children components in case of no error
return this.props.children
}
}
export default ErrorBoundary
ErrorBoundary
组件跟踪一个 hasError
状态。此状态变量的值是一个布尔值。当 hasError
的值为 true
时,ErrorBoundary
组件将渲染一个回退 UI。否则,它将渲染子组件。
创建 ErrorBoundary
组件后,将其导入到 pages/_app.js
文件中,以在你的 Next.js 应用程序中包裹 Component
属性。
// Import the ErrorBoundary component
import ErrorBoundary from '../components/ErrorBoundary'
function MyApp({ Component, pageProps }) {
return (
// Wrap the Component prop with ErrorBoundary component
<ErrorBoundary>
<Component {...pageProps} />
</ErrorBoundary>
)
}
export default MyApp
你可以在 React 的文档中了解更多关于错误边界的信息。
报告错误
要监控客户端错误,请使用像 Sentry、Bugsnag 或 Datadog 这样的服务。
这有帮助吗?