Handling errors with error boundaries ⚠️

Another important tool in your react arsenal are so called, error boundaries, which let you encapsulate parts of your app, so that when errors happen inside that chunk of your app they get nicely processed and display an error message, or something like that. The reason that's important is because with React 16 they changed the behavior, so that when an error happens anywhere in your react componentry react will unmount everything.

Let's say you have these two components right, toothpaste and cap. When you try to put them together there's an error, so react says whoa, I don't know what's going on. I don't want to render something incorrectly, so it unmounts your entire componentry and your whole app fails. But, if you're doing that inside a glass it's going to say, oh okay there's an error inside the glass, but I can still render everything around the glass. I can render Swizec's holding the glass. I can render Swizec talking into the camera, but anything inside the glass gets broken and says, hey there's an error here.

Yeah, you can think of an error boundary as encapsulation for parts of your app, so that you can nicely handle errors. Let's check out what that looks like in code. Now, the trick about error boundaries is that they can only capture errors in their children. They can not capture errors in themselves. They can't capture errors in anything that's asynchronous, so no time outs, no event handlers even. Going to make a generic error boundary component. Then we're going to make a component that causes an error in itself, class based component. We're going to keep error state in our state because that's how we're going to know, oh hey there's been an error. We have to re render and show the error message.

To make this error boundary actually catch our errors we use the component date catch. This at state, and we set error and error in vault. To make a simple counter after we click it a couple of time it's going to throw an error. We now have a counter here. Click. Click. There's been an error and everything washed out. Because we're in Create React App we got this nice error message from Create React App, but otherwise our entire componentry unmounted. We wrap this. We can now see that when an error happens it says something went wrong. Create React App takes over and shows us the nicer error. You can also see that we can [inaudible 00:02:16] all of our error info and get some more information.

Know someone who wants to learn React and its whole ecosystem? Share 👇


Cheers,
~Swizec