unstable_rethrow
unstable_rethrow
可用于避免捕获 Next.js 在尝试处理应用程序代码中抛出的错误时抛出的内部错误。
例如,调用 notFound
函数将抛出 Next.js 内部错误并渲染 not-found.js
组件。但是,如果在 try/catch
语句的 try
块内使用,错误将被捕获,阻止 not-found.js
渲染:
@/app/ui/component.tsx
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.tsx
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 调用也会抛出不应该被开发者捕获的错误。请注意,部分预渲染(PPR)也会影响此行为。这些 API 是:
cookies
headers
searchParams
fetch(..., { cache: 'no-store' })
fetch(..., { next: { revalidate: 0 } })
提示:
- 此方法应该在 catch 块的顶部调用,将错误对象作为其唯一参数传递。它也可以在 Promise 的
.catch
处理程序中使用。- 如果你封装抛出异常的 API 调用并让调用者处理异常,你可能能够避免使用
unstable_rethrow
。- 仅在你的捕获异常可能包括应用程序错误和框架控制的异常(如
redirect()
或notFound()
)时使用unstable_rethrow
。- 任何资源清理(如清除间隔、定时器等)必须在调用
unstable_rethrow
之前或在finally
块内进行。