unstable_rethrow

unstable_rethrow 可用于避免捕获 Next.js 内部错误,这些错误会在处理应用程序代码抛出的错误时产生。

例如,调用 notFound 函数会抛出 Next.js 内部错误并渲染 not-found.js 组件。但如果该调用位于 try/catch 代码块中,错误会被捕获,导致 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 时未包裹在 try/catch 中,则无需使用 unstable_rethrow
  • 任何资源清理操作(如清除间隔、计时器等)必须在调用 unstable_rethrow 之前或在 finally 块中完成