Next.js - unstable_rethrow() Function



The unstable_rethrow() Function

The Next.js unstable_rethrow() function is used to avoid catching internal errors thrown by Next.js when attempting to handle errors thrown in application code. This function is useful for handling errors that are not caught by the Next.js error boundary.

Syntax

The syntax for the unstable_rethrow() function is as follows:

import { unstable_rethrow } from 'next/error'

export default function ErrorBoundary() {
    try {
        throw new Error('Something went wrong')
    } catch (error) {
        unstable_rethrow(error)
    }
}

Parameters

The unstable_rethrow() function accepts one parameter.

  • error: The error object that you want to rethrow.

Return Value

The unstable_rethrow() function does not return any value.

Key Points

  • The unstable_rethrow() 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.
  • The unstable_rethrow() method is only available in the Edge Runtime.
  • Any resource cleanup (like clearing intervals, timers, etc) would have to either happen prior to the call to unstable_rethrow or within a finally block.
  • 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().

Example

In the example below, we are using the unstable_rethrow() function to rethrow an error that is thrown in the catch block of a promise. This will prevent the error from being caught by the Next.js error boundary.

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)
  }
}
Advertisements