unstable_rethrow
unstable_rethrow
can be used to avoid catching internal errors thrown by Next.js when attempting to handle errors thrown from your own application.
For example, given the following code:
import { notFound } from 'next/navigation'
export default async function Component() {
try {
notFound()
await getData()
} catch (err) {
console.error(err)
}
}
In this scenario, console.error
will pick up the error thrown by notFound
, which won't be useful for logging and will prevent
the not-found.js
page from rendering. Instead, you can do this:
import { notFound, unstable_rethrow } from 'next/navigation'
export default async function Component() {
try {
notFound()
await getData()
} catch (err) {
unstable_rethrow(err)
console.error(err)
}
}
If the caught error is meant to be handled by Next.js, unstable_rethrow
will re-throw the error instead of letting it reach your
error handling code.
The following Next.js APIs rely on throwing an error which should be rethrown and handled by Next.js itself:
If a route segment is marked to throw an error unless it's static, a dynamic function call will also throw an error that should similarly not be caught by the developer. Note that Partial Prerendering (PPR) affects this behavior as well. These APIs are:
cookies()
headers()
searchParams
fetch(..., { cache: 'no-store' })
fetch(..., { next: { revalidate: 0 } })
Good to know:
- This method should be called at the top of the catch block, passing the error object as its only argument. It can also be used within a
.catch
handler of a promise.- If you ensure that your calls to APIs that throw are not wrapped in a try/catch then you don't need to use
unstable_rethrow
- Any resource cleanup (like clearing intervals, timers, etc) would have to either happen prior to the call to
unstable_rethrow
or within afinally
block.
Was this helpful?