跳到內容
API 參考函數unstable_rethrow

unstable_rethrow

此功能目前不穩定且可能會變更,不建議用於生產環境。請試用並在 GitHub 上分享您的意見回饋。

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 區塊內發生。