错误错误
原文地址:https://nextjs.org/docs/app/getting-started/error-handling
错误可以分为两类:预期错误和未捕获的异常。本页将引导您了解如何在 Next.js 应用程序中处理这些错误。
1. 处理预期内的错误
预期错误是应用程序正常操作期间可能发生的错误,例如来自服务端表单验证或失败请求的错误。应显式处理这些错误并将其返回给客户端。
1.1 服务端函数
您可以使用 useActionState 钩子来处理服务器函数中的预期错误。
对于这些错误,请避免使用try / catch块并抛出错误。相反,将预期错误建模为返回值。
| app/action.ts |
|---|
| 'use server'
export async function createPost(prevState: any, formData: FormData) {
const title = formData.get('title')
const content = formData.get('content')
const res = await fetch('https://api.vercel.app/posts', {
method: 'POST',
body: { title, content },
})
const json = await res.json()
if (!res.ok) {
return { message: 'Failed to create post' }
}
}
|
您可以将操作传递给 useActionState 钩子并使用返回的 state 来显示错误消息。
| app/ui/form.tsx |
|---|
| 'use client'
import { useActionState } from 'react'
import { createPost } from '@/app/actions'
const initialState = {
message: '',
}
export function Form() {
const [state, formAction, pending] = useActionState(createPost, initialState)
return (
<form action={formAction}>
<label htmlFor="title">Title</label>
<input type="text" id="title" name="title" required />
<label htmlFor="content">Content</label>
<textarea id="content" name="content" required />
{state?.message && <p aria-live="polite">{state.message}</p>}
<button disabled={pending}>Create Post</button>
</form>
)
}
|
1.2 服务端组件
在服务端组件内部获取数据时,您可以使用响应有条件地呈现错误消息或 redirect 。
| app/page.tsx |
|---|
| export default async function Page() {
const res = await fetch(`https://...`)
const data = await res.json()
if (!res.ok) {
return 'There was an error.'
}
return '...'
}
|
1.3 Not found
您可以在路由段内调用 notFound 函数,并使用 not-found.js 文件显示 404 UI。
| app/blog/[slug]/page.tsx |
|---|
| import { getPostBySlug } from '@/lib/posts'
export default async function Page({ params }: { params: { slug: string } }) {
const { slug } = await params
const post = getPostBySlug(slug)
if (!post) {
notFound()
}
return <div>{post.title}</div>
}
|
app/blog/[slug]/not-found.tsxexport default function NotFound() {
return <div>404 - Page Not Found</div>
}
2. 处理不可捕获的错误
未捕获的异常是意外错误,表示在应用程序正常流程中不应发生的错误或问题。这些应该通过抛出错误来处理,然后错误边界会捕获错误。
2.1 嵌套的错误边界
Next.js 使用错误边界来处理未捕获的异常。错误边界捕获子组件中的错误并显示后备 UI,而不是崩溃的组件树。
通过在路由段内添加 error.js 文件并导出 React 组件来创建错误边界:
app/dashboard/error.tsx'use client' // Error boundaries must be Client Components
import { useEffect } from 'react'
export default function ErrorPage({
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>
)
}
错误将向上冒泡到最近的父错误边界,这允许通过将 error.tsx 文件放置在路由层次结构中的不同级别来进行精细的错误处理。
错误边界不会捕获事件处理程序内的错误。它们旨在捕获渲染期间的错误以显示后备 UI,而不是使整个应用程序崩溃。
一般来说,事件处理程序或异步代码中的错误不会由错误边界处理,因为它们在渲染后运行。
要处理这些情况,请手动捕获错误并使用 useState 或 useReducer 存储它,然后更新 UI 以通知用户。
| 'use client'
import { useState } from 'react'
export function Button() {
const [error, setError] = useState(null)
const handleClick = () => {
try {
// do some work that might fail
throw new Error('Exception')
} catch (reason) {
setError(reason)
}
}
if (error) {
/* render fallback UI */
}
return (
<button type="button" onClick={handleClick}>
Click me
</button>
)
}
|
请注意,来自 useTransition 的 startTransition 内未处理的错误将冒泡到最近的错误边界。
| 'use client'
import { useTransition } from 'react'
export function Button() {
const [pending, startTransition] = useTransition()
const handleClick = () =>
startTransition(() => {
throw new Error('Exception')
})
return (
<button type="button" onClick={handleClick}>
Click me
</button>
)
}
|
2.2 全局错误
虽然不太常见,但您可以使用位于根应用程序目录中的 global-error.js 文件来处理根布局中的错误,即使在利用国际化时也是如此。全局错误 UI 必须定义自己的 <html> 和 <body> 标记,因为它在活动时会替换根布局或模板。
| app/global-error.tsx |
|---|
| 'use client' // Error boundaries must be Client Components
export default function GlobalError({
error,
reset,
}: {
error: Error & { digest?: string }
reset: () => void
}) {
return (
// global-error must include html and body tags
<html>
<body>
<h2>Something went wrong!</h2>
<button onClick={() => reset()}>Try again</button>
</body>
</html>
)
}
|