跳到内容
API 参考函数unstable_rethrow

unstable_rethrow

此功能目前不稳定,可能会发生变化,不建议用于生产环境。请尝试使用并在 GitHub 上分享您的反馈。

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 是:

须知:

  • 此方法应在 catch 块的顶部调用,并将错误对象作为其唯一参数。它也可以在 Promise 的 .catch 处理程序中使用。
  • 如果您封装抛出错误的 API 调用并让**调用者**处理异常,则可能可以避免使用 unstable_rethrow
  • 仅当您捕获的异常可能同时包含应用程序错误和框架控制的异常(如 redirect()notFound())时,才使用 unstable_rethrow
  • 任何资源清理(如清除间隔、定时器等)都必须在调用 unstable_rethrow 之前或在 finally 块中进行。