网页
综合
更新时间 2026-10-15 00:00:00
Error Handling
自动蜘蛛
nextjs.org
正文约 2878 字
Errors can be divided into two categories: expected errors and uncaught exceptions. This page will walk you through how you can handle these errors in your Next.js application.
Expected errors are those that can occur during the normal operation of the application, such as those from server-side form validation or failed requests. These errors should be handled explicitly and returned to the client.
You can use the useActionState hook to handle expected errors in Server Functions.
For these errors, avoid using try/catch blocks and throw errors. Instead, model expected errors as return values.
You can pass your action to the useActionState hook and use the returned state to display an error message.
When fetching data inside of a Server Component, you can use the response to conditionally render an error message or redirect.
You can call the notFound function within a route segment and use the not-found.js file to show a 404 UI.
Uncaught exceptions are unexpected errors that indicate bugs or issues that should not occur during the normal flow of your application. These should be handled by throwing errors, which will then be caught by error boundaries.
Next.js uses error boundaries to handle uncaught exceptions. Error boundaries catch errors in their child components and display a fallback UI instead of the component tree that crashed.
Create an error boundary by adding an error.js file inside a route segment and exporting a React component:
Errors will bubble up to the nearest parent error boundary. This allows for granular error handling by placing error.tsx files at different levels in the route hierarchy.
For component-level error recovery, the catchError function lets you create error boundaries that can wrap any part of your component tree:
Then use the returned component as a wrapper in any layout or page:
Error boundaries don't catch errors inside event handlers. They're designed to catch errors during rendering to show a fallback UI instead of crashing the whole app.
In general, errors in event handlers or async code aren’t handled by error boundaries because they run after rendering.
To handle these cases, catch the error manually and store it using useState or useReducer, then update the UI to inform the user.
Note that unhandled errors inside startTransition from useTransition, will bubble up to the nearest error boundary.
While less common, you can handle errors in the root layout using the global-error.js file, located in the root app directory, even when leveraging internationalization. Global error UI must define its own <html> and <body> tags, since it is replacing the root layout or template when active.
Learn more about the features mentioned in this page by reading the API Reference.
Last updated October 15, 2026
Subscribe to our newsletter
Stay updated on new releases and features, guides, and case studies.
本页为82搜索生成的网页快照,内容来自站内索引;演示数据的原文链接仅作示例。