About
This page is about exception handling In React.
When an non-catched javascript error occurs:
Example
- The error boundary react class component 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