Next.js Discord

Discord Forum

Can't catch `notFound()` in Next.js v15.1 ???

Answered
Black Caiman posted this in #help-forum
Open in Discord
Avatar
Black CaimanOP
Previously in v15.0.4, I can catch the notFound() error by its error message (see code below). It doesn't work anymore in v15.1. Is there any behavior changes in notFound()? Or this is a bug?

const NEXT_NOT_FOUND_ERR_MSG = 'NEXT_NOT_FOUND'

export function isNextNotFoundError(error: unknown) {
  return error instanceof Error && error.message === NEXT_NOT_FOUND_ERR_MSG
}

async function fetchData(endpoint: string) {
  const response = await fetch(`${API_URL}${endpoint}`)
  const result = await response.json()
  if (!response.ok) {
    if (response.status === 404) {
      notFound()
    }
    throw new Error(`API error: ${result.message} (${response.status})`)
  }
  return result
}

const { data } = useSuspenseQuery({
  queryKey: ['data', id],
  queryFn: async () => {
    try {
      return await fetchData(id)
    } catch (error) {
      if (isNextNotFoundError(error)) {
        return null
      }
      throw error
    }
  },
})

5 Replies

Answer
Avatar
Black CaimanOP
Maybe we should provide built-in error helper (e.g. isNotFound()) in next/navigation module
Avatar
there is https://nextjs.org/docs/app/api-reference/functions/unstable_rethrow, but that's about the closest thing we currently have
Avatar
@joulev there is <https://nextjs.org/docs/app/api-reference/functions/unstable_rethrow>, but that's about the closest thing we currently have
Avatar
Black CaimanOP
Do you mean like this?
export function isNextNotFoundError(error: unknown) {
  try {
    unstable_rethrow(error)
    return false
  } catch {
    return true
  }
}

But does unstable_rethrow() only take errors from notFound()? What about the upcoming forbidden() and unauthorized()?
Avatar
@Black Caiman Do you mean like this? ts export function isNextNotFoundError(error: unknown) { try { unstable_rethrow(error) return false } catch { return true } } But does `unstable_rethrow()` only take errors from `notFound()`? What about the upcoming `forbidden()` and `unauthorized()`?
Avatar
you can do it without the the wrapper. unstable_rethrow is meant to take parameter from catch(error).

regarding forbidden() and unauthorized(), if it throws an error to perform a redirect, then yees it should capture it too