I am using React router dom version 6.25.1.
My router is defined as
const router = [
{
element: <LayoutThatReturnsOutlet/>,
loader: myLoader,
errorElement: <ErrorElement />,
children: [
{ path: topLevel, element: <TopLevelDashboard /> },
{ path: route1, element: <Element1 /> },
{ path: route2, element: <Element2 /> },
],
},
]
And is used here as follows:
<RouterProvider router={createBrowserRouter(router)} />
But when I try to get the ErrorElement to be returned by doing a simple
throw new Error("Sample error")
in the TopLevelDashboard element, nothing happens (it logs the error to the console but doesn’t show the error element or crash the app – i.e. it just throws the error silently). I have added a path on the top level also in case that was missing, but still no luck (for reference the app’s base URL has /someString/someOtherString format, so running locally looks like localhost:port/someString/someOtherString when on the root route).
I’ve read from the docs that errors ‘bubble up’ to the top level but I’m not sure why they wouldn’t be caught in the error element since there is an outlet on the default template.
The error element does work at the top level (for example if an error is thrown from the loader) but nowhere else.
Trying to define error elements on individual routes is also not working for me, though I’d prefer to have one global error handler.
Is there something obvious I’m missing?
EDIT: After some tinkering I have discovered that the ErrorElement does work, but only when the error is thrown as soon as the element is rendered.
I am trying to throw an error from within a function (i.e. when error condition is true, throw new Error(“etc”)), which is where the errorElement is not catching it
1
I am trying to throw an error from within a function (i.e. when error
condition is true, throw new Error(“etc”)), which is where the
errorElement
is not catching it
Read the errorElement description a bit more closely (emphasis mine):
When exceptions are thrown in loaders, actions, or component
rendering, instead of the normal render path for your Routes
(<Route element>
), the error path will be rendered (<Route errorElement>
) and the error made available withuseRouteError
.
and Route errorElement/ErrorBoundary
When a route throws an exception while rendering, in a
loader
or in
anaction
, this React Element/Component will render instead of the
normalelement
/Component
.
In other words, the errorElement
is used when there is an exception in the rendering of the routed component, or in any of the route loaders/actions.
Any exceptions thrown in callbacks and handlers should be handled normally, e.g. in a try/catch
, a Promise chain’s .catch
blocks, or a “failure”/”onFailure” callback. This means if you have any code in a useEffect
hook callback or a UI event handler like onClick
that potentially throws exceptions, the exceptions should be caught and handled in the component code.