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.
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
Then we start out by importing react, setting up our component and its state.
Next, we will want to add our catch.
Finally, our message and export, that completes the error file.
When correctly completed, your code should look something like this.
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.
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.