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
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