Let's now make sure
that we handle this error on our own
with our own error fallback content instead of using
that default development mode overlay.
And we can handle errors in NextJS
by adding a special file named error.js
and it works just like the not-found.js file.
We can add it anywhere and it will then render its component
whenever an error occurs on the same level
or in some nested page.
So here to handle errors for this page.js file,
we could add an error.js file right next to it.
And then here I'll have my default function.
FilterError could be the component function name.
And then there I'll return a div with an id of error
with an h2 element of an error occurred
or something like this.
And then I'll have a text here where I say invalid path.
And of course, it's totally up to you
how you wanna configure this.
What's important though
is that this now must be a client component,
which you do ensure by adding use client at the top here.
Now, this error.js file
or the component you return in there
must be a client component
and hence you must add use client to the top of this file
because errors can, of course, not just occur
whilst something's happening on this server,
but they may also occur from the client side
because something goes wrong after the page was loaded
and after the user is using the page.
And therefore, the error fallback needs to work on both ends
and client components do work on both ends
on the Server, but also on the client side.
Whereas server components without use client at the top
of the file would only work on the server side.
That's why this error fallback
must be a client component and hence you must add use client
at the top of the file.
And I'll get back to client components
and server components a little bit later again.
I did also cover this important topic
in the essentials section already though.
So with that we have this FilterError function
and this now actually also receives some props,
which are passed in by NextJS.
For example, the error object that was thrown
so that we could also output the actual error.message
instead of invalid path if we wanted to do that.
With that, if we save this,
you see that now I get my own error fallback here
and I can continue using the application
and basically leave that error state.