Global error handling in React Js

Last updated : 23 July 2022

An uncaught Javascript error can crash the entire app. The Error Boundary is a concept introduced to prevent app crashes by catching Javascript errors at the higher application level. Error Boundaries are React class components that wrap up all child components and catch their errors. The componentDidCatch callback detects the errors. Therefore, the Error Boundary component must be a class component. There is no equivalent in functional React components.

Here is an example of an Error Boundary class component.

import React, { ErrorInfo, ReactElement } from "react";
interface ErrorBoundaryState {
    hasError: boolean
    errorMessage: string
}
interface ErrorboundaryProps {
    children: ReactElement
}
export class ErrorBoundaries extends React.Component<ErrorboundaryProps, ErrorBoundaryState>{
    constructor(props: ErrorboundaryProps){
        super(props)
        this.state = {
                        hasError : false,
                        errorMessage: ""
                     }
    }
    componentDidCatch(error: Error, errorInfo: ErrorInfo){
        this.setState({hasError: true})
        this.setState({errorMessage: error.message})
        //Do something with err and errorInfo
    }
    render(): React.ReactNode {
        if(this.state?.hasError){
            return(
                <div className="divClass">
                    <p><h3>ErrorBoundaries</h3></p>
                    {this.state.errorMessage}
                </div>
            )
        }
        return(this.props.children)
    }
}

Next, we must wrap all the components we want to protect against errors.

import { ErrorBoundaries } from "./components/ErrorBoundaries"
import SuccessMessage from "./components/SuccessMessage"
export const App = () => {
return(
  <ErrorBoundaries>
    <SuccessMessage/>
  </ErrorBoundaries>
)
}
export default App

That prevents app crashes due to any errors in the SuccessMessage component. For demo purposes, I throw an error in the useEffect hook. Since this error is not caught within the SuccessMessage component, it will bubble up until it finds the ErrorBoundary component capable of handling the error.

import { useEffect } from "react"
const SuccessMessage = () =>{
  useEffect(() => {
    throw new Error("Api did not respond!")// throwing an error
  })
  return(
          <div>
            <span>Your Account has been created successfully</span>
            <button>Go to account</button>
          </div>
  )
}
export default SuccessMessage
React js global error handling with error boundaries
Figure 1: React js global error handling with error boundaries
Lance
By: Lance
Lance is a software engineer with over 15 years of experience in full-stack software development.
Read more...

Leave a comment

No Comments