Error Handling 错误处理
The error.js file convention allows you to gracefully handle unexpected runtime errors in nested routes.
error.js 文件约定允许您优雅地处理嵌套路由中的意外运行时错误。
Automatically wrap a route segment and its nested children in a React Error Boundary.
自动将路由段及其嵌套子项包装在 React 错误边界中。Create error UI tailored to specific segments using the file-system hierarchy to adjust granularity.
使用文件系统层次结构调整粒度,创建针对特定段的错误 UI。Isolate errors to affected segments while keeping the rest of the application functional.
将错误隔离到受影响的段,同时保持应用程序的其余部分正常运行。Add functionality to attempt to recover from an error without a full page reload.
添加功能以尝试从错误中恢复,而无需完全重新加载页面。
Create error UI by adding an error.js file inside a route segment and exporting a React component:
通过在路由段内添加 error.js 文件并导出 React 组件来创建错误 UI:
'use client' // Error components must be Client Components
import { useEffect } from 'react'
export default function Error({
error,
reset,
}: {
error: Error & { digest?: string }
reset: () => void
}) {
useEffect(() => {
// Log the error to an error reporting service
console.error(error)
}, [error])
return (
<div>
<h2>Something went wrong!</h2>
<button
onClick={
// Attempt to recover by trying to re-render the segment
() => reset()
}
>
Try again
</button>
</div>
)
}
1.How error.js Works 如何 error.js 工作
error.js
automatically creates a React Error Boundary that wraps a nested child segment orpage.js
component.error.js
自动创建一个 React 错误边界,该边界包装一个嵌套的子段或page.js
组件。The React component exported from the
error.js
file is used as the fallback component.
从error.js
文件导出的 React 组件用作后备组件。If an error is thrown within the error boundary, the error is contained, and the fallback component is rendered.
如果错误边界内引发错误,则错误将被包含,并且将呈现后备组件。When the fallback error component is active, layouts above the error boundary maintain their state and remain interactive, and the error component can display functionality to recover from the error.
当后备错误组件处于活动状态时,错误边界上方的布局将保持其状态并保持交互性,并且错误组件可以显示从错误中恢复的功能。
2.Recovering From Errors 从错误中恢复
The cause of an error can sometimes be temporary. In these cases, simply trying again might resolve the issue.
错误的原因有时可能是暂时的。在这种情况下,只需重试即可解决问题。
An error component can use the reset() function to prompt the user to attempt to recover from the error. When executed, the function will try to re-render the Error boundary's contents. If successful, the fallback error component is replaced with the result of the re-render.
错误组件可以使用 reset() 函数提示用户尝试从错误中恢复。执行时,该函数将尝试重新渲染错误边界的的内容。如果成功,则将回退错误组件替换为重新渲染的结果。
'use client'
export default function Error({
error,
reset,
}: {
error: Error & { digest?: string }
reset: () => void
}) {
return (
<div>
<h2>Something went wrong!</h2>
<button onClick={() => reset()}>Try again</button>
</div>
)
}
3.Nested Routes 嵌套路由
React components created through special files are rendered in a specific nested hierarchy.
通过特殊文件创建的 React 组件以特定的嵌套层次结构呈现。
For example, a nested route with two segments that both include layout.js and error.js files are rendered in the following simplified component hierarchy:
例如,包含两个段的嵌套路由(都包含 layout.js 和 error.js 文件)以以下简化的组件层次结构呈现:
The nested component hierarchy has implications for the behavior of error.js files across a nested route:
嵌套组件层次结构对嵌套路由中的 error.js 文件的行为有影响:
-Errors bubble up to the nearest parent error boundary. This means an error.js file will handle errors for all its nested child segments. More or less granular error UI can be achieved by placing error.js files at different levels in the nested folders of a route.
错误会冒泡到最近的父错误边界。这意味着 error.js 文件将处理所有嵌套子片段的错误。可以通过在路由的嵌套文件夹中不同级别放置 error.js 文件来实现更精细或更粗略的错误 UI。
-An error.js boundary will not handle errors thrown in a layout.js component in the same segment because the error boundary is nested inside that layout's component.
error.js 边界不会处理在同一片段的 layout.js 组件中引发的错误,因为错误边界嵌套在该布局的组件中。
4.Handling Errors in Layouts 处理布局中的错误
error.js boundaries do not catch errors thrown in layout.js or template.js components of the same segment. This intentional hierarchy keeps important UI that is shared between sibling routes (such as navigation) visible and functional when an error occurs.
error.js 边界不会捕获同一片段的 layout.js 或 template.js 组件中引发的错误。这种有意的层次结构可确保在发生错误时,在兄弟路由之间共享的重要 UI(例如导航)保持可见和可用。
To handle errors within a specific layout or template, place an error.js file in the layout's parent segment.
要在特定布局或模板中处理错误,请将 error.js 文件放在布局的父段中。
To handle errors within the root layout or template, use a variation of error.js called global-error.js.
要在根布局或模板中处理错误,请使用 error.js 的变体,称为 global-error.js 。
5.Handling Errors in Root Layouts 处理根布局中的错误
The root app/error.js boundary does not catch errors thrown in the root app/layout.js or app/template.js component.
根 app/error.js 边界不会捕获在根 app/layout.js 或 app/template.js 组件中引发的错误。
To specifically handle errors in these root components, use a variation of error.js called app/global-error.js located in the root app directory.
要专门处理这些根组件中的错误,请使用位于根 app 目录中的名为 app/global-error.js 的 error.js 变体。
Unlike the root error.js, the global-error.js error boundary wraps the entire application, and its fallback component replaces the root layout when active. Because of this, it is important to note that global-error.js must define its own <html> and <body> tags.
与根 error.js 不同, global-error.js 错误边界封装了整个应用程序,其后备组件在激活时替换根布局。因此,务必注意 global-error.js 必须定义其自己的 <html> 和 <body> 标签。
global-error.js is the least granular error UI and can be considered "catch-all" error handling for the whole application. It is unlikely to be triggered often as root components are typically less dynamic, and other error.js boundaries will catch most errors.
global-error.js 是最不精细的错误 UI,可以被视为整个应用程序的“一网打尽”错误处理。它不太可能经常触发,因为根组件通常不太动态,其他 error.js 边界会捕获大多数错误。
Even if a global-error.js is defined, it is still recommended to define a root error.js whose fallback component will be rendered within the root layout, which includes globally shared UI and branding.
即使定义了 global-error.js ,仍然建议定义一个根 error.js ,其后备组件将在根布局中呈现,其中包括全局共享的 UI 和品牌。
'use client'
export default function GlobalError({
error,
reset,
}: {
error: Error & { digest?: string }
reset: () => void
}) {
return (
<html>
<body>
<h2>Something went wrong!</h2>
<button onClick={() => reset()}>Try again</button>
</body>
</html>
)
}
6.Handling Server Errors 处理服务器错误
If an error is thrown inside a Server Component, Next.js will forward an Error object (stripped of sensitive error information in production) to the nearest error.js file as the error prop.
如果在服务器组件内部抛出错误,Next.js 会将 Error 对象(在生产环境中剥离敏感错误信息)转发到最近的 error.js 文件作为 error 属性。
a.Securing Sensitive Error Information 保护敏感错误信息
During production, the Error object forwarded to the client only includes a generic message and digest property.
在生产过程中,转发给客户端的 Error 对象仅包含一个通用的 message 和 digest 属性。
This is a security precaution to avoid leaking potentially sensitive details included in the error to the client.
这是为了避免将错误中包含的潜在敏感细节泄露给客户端的安全预防措施。
The message property contains a generic message about the error and the digest property contains an automatically generated hash of the error that can be used to match the corresponding error in server-side logs.
message 属性包含有关错误的通用消息, digest 属性包含自动生成的错误哈希,可用于匹配服务器端日志中的相应错误。
During development, the Error object forwarded to the client will be serialized and include the message of the original error for easier debugging.
在开发期间,转发给客户端的 Error 对象将被序列化,并包含原始错误的 message 以便于调试。