I'm working on a project using Next.js 13 and the app directory structure. I've created error.tsx
and not-found.tsx
pages in the app/sample directory to handle errors and not-found scenarios. However, when I try to use these pages, they're not displaying as expected.
Here's the code for my error and not-found pages:
app/sample/error.tsx:
'use client'
import React from 'react'
export default function Error({
error,
reset,
}: {
error: Error
reset: () => void
}) {
React.useEffect(() => {
console.log('logging error:', error)
}, [error])
return (
<div className="space-y-4">
<h2 className="text-lg font-bold">Error</h2>
<p className="text-sm">{error?.message}</p>
<div>
<button onClick={() => reset()}>Try Again</button>
</div>
</div>
)
}
app/sample/not-found.tsx:
export default function NotFound() {
return (
<div className="space-y-4">
<h2 className="text-lg font-bold">Not Found</h2>
<p className="text-sm">Could not find requested resource</p>
</div>
)
}
In my app/sample/page.tsx
file, I'm deliberately triggering an error like this:
'use client'
export default function Sample() {
const error = () => {
throw new Error(new Date().toISOString())
}
return (
<main className="flex flex-col items-center justify-between p-24">
Sample
<button onClick={error}>Throw Error</button>
</main>
)
}
The issue I'm facing is that when I invoke the error by clicking the "Throw Error"
button on the page accessed via localhost:3000/sample
, I expect to see the custom error page I've defined, but instead, I get a Next.js pop-up notification on the bottom left of the screen that informs me of the error.
I'm wondering if I've missed any configuration or if there's something I need to do differently in Next.js 13 to properly display the custom error and not-found pages. Any guidance or suggestions on how to troubleshoot and resolve this issue would be greatly appreciated.
Thank you in advance!
Because error.js uses react error boundaries and they don't catch errors from event handlers. Check the yellow note here: https://legacy.reactjs.org/docs/error-boundaries.html
You could use an error state and throw the error when this state changes
I had a similar issue... I couldn't understand the cause for a long time, and through the process of elimination, I concluded (in my case) that the problem was with the <Providers>
in layout.tsx
(Providers.tsx
→ that wraps {children} with react-redux
store Provider
).
Because of it, the display for not-found.tsx
wasn't triggering. With other errors - same!
→ I moved it to a separate component and wrapped only those components that use it
...
upd; right way to trigger not-found:
import { notFound } from 'next/navigation';
...
<button onClick={notFound}>Throw 404 Error</button>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With