In this tutorial, you will learn about the error boundary pattern. The error boundary pattern is a technique you can apply that will prevent random exceptions taking down the whole page. Speaking from experience, there is nothing worse when someone reports a page keeps crashing and you realize it's over some nuanced code you forgot to use with optional chaining. To picture a common scenario, an end-point is updated with a breaking change. The new data format returned by the API breaks your code and an exception is thrown. Without a proper way of dealing with the error, the page crashes.
The error boundary pattern is the name given to a type of component you can create that will handle errors thrown within your application. As of React v16, any unhandled errors will unmount the entire application. An error boundary component will prevent that from happening. Imagine an error gets thrown somewhere in the component hierarchy. If an exception is not handled within the component that threw it, the execution will bubble up. If the parent component does not handle the exception, again the exception will be bubbled up. This process will repeat until the root of the application is reached. If nothing is done to resolve the situation, the application will unmount.
An error boundary is a component that you sits at the top of your application stack that will process these unhandled exceptions gracefully. Let's look at a very basic example of an error-boundary component:
The import part of the component can be found within componentDidCatch(). If this function is triggered then 'hasErrors' is set to true. When this happens the component will be re-rendered and in this example, a very crappy error message will be displayed. Catching and error this way is a lot more desirable than having the application break. The ErrorBoundary can then be used as a regular component:
Another interesting point to keep in mind is that react will only catch exceptions thrown by a component. If you need to make API/async calls within your application, these exceptions may not be caught using 'componentDidCatch()'. Take this crude example:
If mockFetch is used within a component, an error will be thrown 9 seconds after it is called. Even if you use an error boundary when this exception is thrown 'componentDidCatch()' will not catch-it and the application will crash. This is expected behavior by the framework. React will only catch errors that occur within a component. As this error is occurred outside of the normal life-cycle request it will cause you issues. To get around this issue you can use 'window.onerror', like so:
Adding this additional error-handling means the error boundary will capture all exceptions thrown by your application. You will no longer that your whole application will crash. Enjoy!