The red screen of terror… the huge ambiguous errors… the mounting fear of “Oh God, I broke it”; as developers, these errors can strike terror in us. Luckily we have the tools to fix it. Our users, however, are left in the dark about what happened and don’t know how to fix it! Pan left, our hero, Error Boundaries, swoops in for the save. Or in some special cases, Dead Pool... It depends on the day.

Photo by Ayo Ogunseinde on Unsplash

In digging in Udemy courses and the React Docs, I found a glorious thing called Error Boundaries. I found this little guy saves some of that terror for another day. Do note that Error Boundaries are a feature of React 16+.

How to set it up

We first will set up a file that I call ErrorBoundries and within that file a JavaScript file called ErrorBoundries.js. We did capitalize this on purpose.

Then we start out by importing react, setting up our component and its state.

Component structure
Component structure

Next, we will want to add our catch.

Catch component
Catch component

Finally, our message and export, that completes the error file.

JSX error message
JSX error message
JSX error message

When correctly completed, your code should look something like this.

Full error component
Full error component

Once your error message is done, you then wrap whatever component you want to have the error message. In my case a Person card. You will want to only wrap things in error boundaries when you are certain something will fail and there is nothing you as a developer can do about it.

Error Boundaries
Error Boundaries

And magic! While we are still in development mode, we will still see a scary error message. Thankfully, when we deploy, our users will not have to face that terror. Instead, they will see our error message that we set up! If you want to learn more check out https://reactjs.org/docs/error-boundaries.html.

I work as a UX Designer. I adore games (video and board), learning, travel, and personal wellness.