Catching errors with error boundary components
Error boundary components are just React components that implement the componentDidCatch
life cycle method to catch errors in their children. They catch errors in constructor
methods when a class component is initialized but fails, in life cycle methods, and while rendering. Errors that cannot be caught are from asynchronous code, event handlers, and errors in the error component boundary itself.
The componentDidCatch
life cycle method receives two arguments: the first one is an error
object while the second received argument is an object containing a componentStack
property with a friendly stack trace that describes where in the React tree a component failed.
Getting ready
In this recipe, you will build an error boundary component and provide a fallback UI when there is an error while rendering. Before you start, create a new package.json
file with the following content:
{ "scripts": { "start": "parcel serve -p 1337 index.html" }, ...