unstable_rethrow 可以用来避免捕获 Next.js 在尝试处理您的应用程序代码中抛出的错误时所抛出的内部错误。
例如,调用 notFound 函数会抛出一个 Next.js 内部错误并渲染 not-found.js 组件。然而,如果在一个 try/catch 语句的 try 块内部使用,该错误将被捕获,阻止 not-found.js 渲染:
import { notFound } from 'next/navigation'
export default async function Page() {
try {
const post = await fetch('https://.../posts/1').then((res) => {
if (res.status === 404) notFound()
if (!res.ok) throw new Error(res.statusText)
return res.json()
})
} catch (err) {
console.error(err)
}
}您可以使用 unstable_rethrow API 来重新抛出内部错误并继续执行预期的行为:
import { notFound, unstable_rethrow } from 'next/navigation'
export default async function Page() {
try {
const post = await fetch('https://.../posts/1').then((res) => {
if (res.status === 404) notFound()
if (!res.ok) throw new Error(res.statusText)
return res.json()
})
} catch (err) {
unstable_rethrow(err)
console.error(err)
}
}以下 Next.js API 依赖于抛出错误,这些错误应由 Next.js 自身重新抛出并处理:
如果路由段被标记为抛出错误,除非它是静态的,那么动态 API 调用也将抛出一个开发者同样不应捕获的错误。请注意,部分预渲染 (Partial Prerendering, PPR) 也会影响此行为。这些 API 包括:
cookiesheaderssearchParamsfetch(..., { cache: 'no-store' })fetch(..., { next: { revalidate: 0 } })须知:
- 此方法应在
catch块的顶部调用,将错误对象作为其唯一参数传入。它也可以在 Promise 的.catch处理程序中使用。- 如果您封装了会抛出错误的 API 调用,并让调用者处理异常,则可以避免使用
unstable_rethrow。- 仅当您捕获的异常可能同时包含应用程序错误和框架控制的异常(例如
redirect()或notFound())时,才使用unstable_rethrow。- 任何资源清理(例如清除间隔、计时器等)都必须在调用
unstable_rethrow之前进行,或在finally块中进行。