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 區塊中執行。