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 是:
cookiesheaderssearchParamsfetch(..., { cache: 'no-store' })fetch(..., { next: { revalidate: 0 } })
須知:
- 此方法應在 catch 塊的頂部呼叫,並將錯誤物件作為其唯一引數。它也可以在 Promise 的
.catch處理程式中使用。- 如果您封裝丟擲錯誤的 API 呼叫並讓**呼叫者**處理異常,則可能可以避免使用
unstable_rethrow。- 僅當您捕獲的異常可能同時包含應用程式錯誤和框架控制的異常(如
redirect()或notFound())時,才使用unstable_rethrow。- 任何資源清理(如清除間隔、定時器等)都必須在呼叫
unstable_rethrow之前或在finally塊中進行。
這有幫助嗎?