NNext.js 中文网 GitHub

unstable_rethrow

unstable

unstable_rethrow 函数的 API 参考。

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 的调用也会抛出一个同样不应被开发者捕获的错误。请注意,Partial Prerendering (PPR) 也会影响此行为。这些 API 包括:

小知识:

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