We are now able to replace our custom ErrorBoundary
with the ErrorBoundary
component from react-error-boundary
— but there are some features that we lost. Specifically, we don’t have error logging and the reset component feature!
Thankfully, react-error-boundary
has built-in implementations for adding in these important features. Let’s take a look.
First, we can see how to add error logging with the onError
prop:
<ErrorBoundary onError={logError} FallbackComponent={ErrorFallback}> <MyComponent/> </ErrorBoundary>
In this example, we add the onError
prop with our logging function logError
as the value. onError
will send along two familiar values to the provided function: error
and errorInfo
. Notice that these are the same arguments passed to the componentDidCatch()
lifecycle method.
Next, we can look at resetting the ErrorBoundary with the resetErrorBoundary
prop:
function ErrorFallback({ error, resetErrorBoundary }) { return ( <div> <h2>An error occurred in the app!!</h2> <p>Error: {error.message}</p> <button onClick={resetErrorBoundary}> Reset </button> </div> ); }
When our ErrorBoundary
renders a fallback component, it will pass in two values as props: error
and resetErrorBoundary
.
error
is the Error object itself which can be useful if we want to display theerror.message
.resetErrorBoundary
is a callback function that will reset the internal error state of theErrorBoundary
itself. This callback can be assigned to theonClick
prop of the button element in our fallback UI.
With this code in place, when the user clicks on the “Reset” button in our fallback UI, the ErrorBoundary
will reset and attempt to re-render the broken child component.
Note: If you take a look at the source code for this feature, you can see that it’s basically the same as our own implementation!
Instructions
Let’s add logging and resetting back into our application. First add an onError
prop to each of the ErrorBoundary
components. The value of this prop should be the imported logError
function. Remember to pass in logError
as a function, without having invoked it.
Test out your “Bad Switch” buttons, they should now produce the familiar red error-logging message.
Next, let’s modify the ErrorFallback
component. In the parameter list, destructure the error
and resetErrorBoundary
props.
Below the <h2>
element and inside the <div>
returned by your ErrorFallback
component, add in a <button>
element with the text Reset
. It should have an onClick
property with a value of resetErrorBoundary
. Again, no need to call this function when assigning to the onClick
property.
Finally, add a <p>
element that renders the .message
property of the error
prop like so:
<p>Error: {error.message}</p>
With everything in place, test your code!