Capítulo 181 de 456
Evita capturar erros internos do Next.js (como notFound(), redirect()) quando você envolve código em try/catch para tratar erros da própria aplicação.
catch (ou num .catch de Promise), repassa erros internos controlados pelo framework antes de tratar o resto.notFound(), redirect(), permanentRedirect().cookies, headers, searchParams, fetch(..., { cache: 'no-store' }), fetch(..., { next: { revalidate: 0 } }).// Sem unstable_rethrow: notFound() é engolido pelo catch, not-found.js não renderiza
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)
}
}
notFound() capturado por engano dentro de um catch genérico.// Com unstable_rethrow: erro interno passa, erro de app é tratado
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)
}
}
try/catch genérico envolvendo notFound()/redirect() sem unstable_rethrow: suprime a navegação/erro esperado silenciosamente.unstable_rethrow: código após ela só roda se não for erro interno — cleanup deve ficar antes ou em bloco finally.catch pode receber tanto erros de aplicação quanto exceções controladas pelo framework (redirect/notFound/etc).unstable_rethrow de todo.catch.