Learn

Rendering a fallback UI is a valuable upgrade to the user experience. However, when an error occurs, it’s important for developers (and those brave users who submit bug reports) to be able to see the error information and make a plan for preventing those errors from happening again.

Error logging is implemented in an ErrorBoundary component using the componentDidCatch() lifecycle method:

componentDidCatch(error, errorInfo) { console.log(error); console.log(errorInfo.componentStack); }

This lifecycle method is called by React after an error has been thrown by one of its descendants. When called, it receives an error object representing the thrown error. It also receives an errorInfo object with a .componentStack property. This property is incredibly useful as it contains a stack trace showing the history of rendered components that led to the error.

Error: Why do we even have this switch?
in LightSwitch (created by App)
in ErrorBoundary (created by App)
in div (created by App)
in App

By logging this stack trace, we can more accurately hunt down the source of the error.

How your team decides to use the componentDidCatch() method to log the error information can vary widely. When testing out this feature, you may decide to simply print the error to the console. However, in production applications, this info is often sent to a server for monitoring, alerting, and debugging.

Now it’s your turn to try!

Instructions

1.

Inside your ErrorBoundary component, define the componentDidCatch() lifecycle method. It should receive two parameters: error and errorInfo.

2.

We’ve written a custom function, logError, to handle errors for us. It has been imported for you at the top of the index.js file (feel free to take a look at error-logging-service.js to see its implementation). Calling logError() with error and errorInfo as arguments will display an error message in a red pop-out. The component stack trace is also shown.

Inside your componentDidCatch() method, call logError() and pass in the error and errorInfo values.

3.

Finally, test your application. When you press the error buttons for the light switches 1-3, you should see the red pop-up appear with the error message and stack trace revealing which component threw the error. Notice that light switch 4 still is unprotected and will cause the entire application to crash.

Sign up to start coding

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?