unstable_rethrow
unstable_rethrow 函数的 API 参考。
此功能目前尚不稳定,可能会发生变化,不建议用于生产环境。欢迎试用并在 GitHub 上分享你的反馈。
unstable_rethrow 可用于避免在尝试处理应用程序代码中抛出的错误时,捕获 Next.js 抛出的内部错误。
例如,调用 notFound 函数会抛出 Next.js 内部错误并渲染 not-found.js 组件。但是,如果在 try/catch 语句的 try 块中使用,该错误会被捕获,从而阻止 not-found.js 渲染:
@/app/ui/component.tsxtsx
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 重新抛出该内部错误,并继续按预期行为执行:
@/app/ui/component.tsxtsx
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 自身处理:
如果某个路由段被标记为除非是静态的否则抛出错误,那么 Request-time API 调用也会抛出一个错误,该错误同样不应被开发者捕获。请注意,部分预渲染(PPR)也会影响此行为。这些 API 包括:
cookiesheaderssearchParamsfetch(..., { cache: 'no-store' })fetch(..., { next: { revalidate: 0 } })
须知:
- 应在 catch 块的开头调用此方法,并将错误对象作为其唯一参数传入。它也可以在 promise 的
.catch处理器中使用。- 如果你封装会抛出错误的 API 调用,并让调用方处理异常,也许可以避免使用
unstable_rethrow。- 仅当捕获的异常可能同时包含应用程序错误和框架控制的异常(如
redirect()或notFound())时,才使用unstable_rethrow。- 任何资源清理(如清除 interval、定时器等)都必须在调用
unstable_rethrow之前完成,或在finally块中进行。