Handling errors in Remix forms

It is at all times annoying in case your software throws unexpected errors.

On the whole, it is good recommendation to construct in the most typical error catching early on. Nevertheless, there may be some generic errors you may’t at all times see coming.

Fortunately for us, Remix will catch most of those errors and might render them to the closest ErrorBoundary field we outline.



Making a root error boundary

From my perspective, you may at all times wish to add a root error boundary to your code, that is the topmost degree, so if an error is thrown top-level, this one will at all times have the ability to catch it.

To create one in all these root error boundaries, open up the root.tsx file.

Based on the docs, it is best to render a full HTML for the basis error boundary as it should mount and unmount on the render of this error.
By gaining access to the <Meta />, <Hyperlinks />, and <Script /> tags, it’d have the ability to re-render.

Let’s add the next perform to this root file:

export perform ErrorBoundary({ error }) {
  return (
    <html>
      <head>
        <title>Oh no!</title>
        <Meta />
        <Hyperlinks />
      </head>
      <physique className='m-4'>
        <h1 className='text-2xl'>One thing went improper!</h1>
        <p>{error.message}</p>
        <Scripts />
      </physique>
    </html>
  );
}
Enter fullscreen mode

Exit fullscreen mode

Let’s attempt it out and see what occurs; I added this specific error in app/routes/admin/posts/index.tsx.

export perform loader() {
  throw new Error('I'm a failure!');
}
Enter fullscreen mode

Exit fullscreen mode

And if we now open this web page, we get hit by the next error.

That is already manner higher than not throwing a customized error.
The draw back is obstructing the whole web page whereas our error is simply thrown down the road.



Including nested error boundaries

And that is the place Remix sort of blows my thoughts. It helps a number of error boundaries!

Remix will begin on the lookout for the closest error boundary to render the error when an error is thrown.

We might add an error boundary in the identical file we throw it in in our case.

export perform ErrorBoundary({ error }) {
  return (
    <div className='bg-red-100 border border-red-300 p-4'>
      <h1 className='text-2xl'>One thing went improper!</h1>
      <p>{error.message}</p>
    </div>
  );
}
Enter fullscreen mode

Exit fullscreen mode

Now refresh the web page and see what occurs.

Nested error boundary

Wow, the error is simply proven within the particular nested route!
The opposite components of our software are nonetheless working as anticipated.

You’ll find this instance code on GitHub.



Thanks for studying, and let’s join!

Thanks for studying my weblog. Be happy to subscribe to my e-mail publication and join on Facebook or Twitter



Add a Comment

Your email address will not be published. Required fields are marked *