How to catch exceptions/errors in React?

Deep Dive in Error Handling with React

About

This page is about exception handling In React.

When an non-catched javascript error occurs:

  • React remove its UI (ie stop rendering the tree) from the screen.
  • And show a special component known as error boundary 1) that:
    • catches the error
    • and lets you show an error message (known as fallback UI)

Example

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {
    // Update state so the next render will show the fallback UI.
    return { hasError: true, message: error.message };
  }

  componentDidCatch(error, info) {
    // Example "componentStack":
    //   in ComponentThatThrows (created by App)
    //   in ErrorBoundary (created by App)
    //   in div (created by App)
    //   in App
    // logErrorToMyService(error, info.componentStack);
    console.log(error.message)
  }

  render() {
    if (this.state.hasError) {
      // You can render any custom fallback UI
      return this.props.fallback(this.state.message);
    }

    return this.props.children;
  }
}
  • The fallback component
function FallbackUI(message){
  return (
    <div style={{border: '1px solid red', padding: '1rem', borderRadius: '10px', width: 'max-content'}}>
      <p><b>Something went wrong!!.</b></p>
      <p><b>Error:</b></p>
      <p><mark>{message}</mark></p>
    </div>
  )
}
  • The component that throws an error
function ComponentWithError() {
  throw new Error('An error message from the component (ComponentWithError)')
}
  • The App component that ties all components together and that we will render
function App() {
  return (
    <ErrorBoundary fallback={FallbackUI}>
      <ComponentWithError/>
    </ErrorBoundary>
  )
}
  • Result:

Characteristic

A error boundary component can only be written as class component or you can install the wrapper library react-error-boundary





Discover More
What is a React Class Component?

A React Class component is a React component created via a Javascript. Even if class component are now an old technology, they are still used and are also still mandatory knowledge if you want to create...



Share this page:
Follow us:
Task Runner