DEV Community

Mayuran
Mayuran

Posted on

React Error Boundary - An Intro

Preface

My team and I are currently working on an analytics dashboard for a payment gateway at work. We are using ElasticSearch to comb through large amounts of raw data, aggregate that, then provide useful insights, displayed on a beautiful UI built using ReactJS. The application's backend is supported by NodeJS + Express and MongoDB for some data persistence.

After working on it for ~4 months, I finally got to demo it, to other team mates. It wasn't perfect, but I wanted to show what we have achieved so far. I showed our really fast search feature. I hit enter after typing the search term, expected it to load the results in blazing fast speed, but instead I got a white screen. The entire app had crashed, with no information about what went wrong. This was embarrassing, and I just found out that we hadn't thought of error messages.

Context

We have unit tests, code reviews and manual QA testing to prevent the bad stuff like this from happening. BUT, it did. I figured out the root cause using Chrome Dev Tools, and quickly resolved it, but this wasn't enough. What if this happens at a real demo. I needed to do something better.

Why did the app crash?

In one of the component's render code I was trying to access a property on an undefined object. That throws an exception: TypeError. And if you don't handle this exception, then you get the infamous Uncaught TypeError in the browser console.

Error Message Screenshot

But, why the did the app crash ?

To answer this, let's dig into the code a bit more. In the below pen, as you click the button the status updates, but the third time you click it you will see a blank screen, because the app crashes. Open the pen in full view and inspect your browser console, and you'll see the error occurred in the BadgeComponent.

Why would an error that occurred in one child component crash the entire application? The React Team has an answer to that - but in short and quite obviously, leaving a broken UI is bad UX, so it is better to just remove the entire UI.

Enter Error Boundary

A blank UI with nothing to see is also bad UX, and to answer that React 16 introduces Error Boundary. It is essentially a component that is able to handle an error that occurs in a child component, and display/render a fallback UI. There are plenty of great posts online explaining how to use one, but here's a quick pen I made that gracefully handles the error we see in the above pen.

In my next post in this series, I'll talk about how Error Boundary works, and show you what to do after an error has been caught by the Error Boundary Component.

Top comments (1)

Collapse
 
aissabouguern profile image
Aissa BOUGUERN

Thank you,
This is a small and very focusing article.