Skip to main content

unstable_rethrow

unstable_rethrow 可用于避免在尝试处理应用代码中抛出的错误时捕获 Next.js 抛出的内部错误。

¥unstable_rethrow can be used to avoid catching internal errors thrown by Next.js when attempting to handle errors thrown in your application code.

例如,调用 notFound 函数将引发内部 Next.js 错误并渲染 not-found.js 组件。但是,如果在 try/catch 块内使用,错误将被捕获,从而阻止 not-found.js 渲染:

¥For example, calling the notFound function will throw an internal Next.js error and render the not-found.js component. However, if used inside a try/catch block, the error will be caught, preventing not-found.js from rendering:

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 重新抛出内部错误并继续执行预期行为:

¥You can use unstable_rethrow API to re-throw the internal error and continue with the expected behavior:

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 本身重新抛出并处理:

¥The following Next.js APIs rely on throwing an error which should be rethrown and handled by Next.js itself:

如果路由段被标记为抛出错误(除非它是静态的),则动态 API 调用也会抛出错误,同样开发者也不应该捕获该错误。请注意,部分预渲染 (PPR) 也会影响此行为。这些 API 是:

¥If a route segment is marked to throw an error unless it's static, a Dynamic API call will also throw an error that should similarly not be caught by the developer. Note that Partial Prerendering (PPR) affects this behavior as well. These APIs are:

很高兴知道:

¥Good to know:

  • 此方法应在 catch 块的顶部调用,并将错误对象作为其唯一参数传递。它也可以用于 promise 的 .catch 处理程序中。

    ¥This method should be called at the top of the catch block, passing the error object as its only argument. It can also be used within a .catch handler of a promise.

  • 如果你确保对抛出的 API 的调用没有封装在 try/catch 中,则无需使用 unstable_rethrow

    ¥If you ensure that your calls to APIs that throw are not wrapped in a try/catch then you don't need to use unstable_rethrow

  • 任何资源清理(如清除间隔、计时器等)都必须在调用 unstable_rethrow 之前或在 finally 块内进行。

    ¥Any resource cleanup (like clearing intervals, timers, etc) would have to either happen prior to the call to unstable_rethrow or within a finally block.