Advertisement
Intermediate React, Error Boundaries

How do you log error details when an error boundary catches an error?

Short answer

You add the componentDidCatch method to your error boundary class, which receives the actual error object and information about where it happened. This is a good place to send the error details to a logging service so your team can find and fix the problem later.

Save React mock interview
Advertisement
AModel answer
You add the componentDidCatch method to your error boundary class, which receives the actual error object and information about where it happened. This is a good place to send the error details to a logging service so your team can find and fix the problem later.
class ErrorBoundary extends React.Component {
  state = { hasError: false };
  static getDerivedStateFromError() {
    return { hasError: true };
  }
  componentDidCatch(error, info) {
    logErrorToService(error, info.componentStack);
  }
  render() {
    if (this.state.hasError) return <p>Something went wrong</p>;
    return this.props.children;
  }
}
Real-world example
A team's error boundary automatically sends every caught error, along with which component it happened in, to their monitoring service, so they find out about real user problems before customers even need to report them.
Likely follow-ups
  • What information does componentStack actually tell you about where the error happened?
  • How would you also show a button letting the user try reloading the broken section?
Related topics