Error handling in React
Error handling should be the most important part of the large scale application so today weāll show you the error handling in React using `componentDidCatch` method.
There are different types of error handling exist in the application but here weāll handle the javascript error that occurs in React components.
Checkout more articles on ReactJS
- How to add DateTimePicker in ReactJS
- Animated sticky header on scroll in React
- How to deploy a react app to node server
- How to reset the state of a Redux store
- Implement Google Maps in ReactJS
By default the white screen will display when error will occur in the react application. So itās good practice to handle an error to display a helpful message on screen. You can also log those messages for further use.
Steps to handle an errors in React
1. Setup react application
Letās set up a simple react application using create-react-app. If you donāt know how to do it then refer to the below link.
2. Create error handler component
We will create a component name as `ErrorHandler.js` that helps us to handle javascript error anywhere from the child components. Itās introduced as an error boundary.
In this component, we need to use `componentDidCatch(error, info)` lifecycle method to handle an error and display a fallback UI via state variable.
ErrorHandler.js
import React, { Component } from "react";
class ErrorHandler extends Component {
constructor(props) {
super(props);
this.state = {
hasError: false
};
}
componentDidCatch(error, info) {
// Handle fallback UI
this.setState({ hasError: true });
// Manage error logs
// logErrorStack(error, info);
}
render() {
if (this.state.hasError) {
return <div class="error-msg-screen">
<h2 class="text-uppercase">Oops!</h2>
<h3 class="text-uppercase mb-3">Something went wrong</h3>
<p class="mb-4">
Brace yourself till we get the error fixed.<br>
You may also refresh the page or try again later.
</p>
<button type="button" class="btn btn-secondary btn-sm mr-2">Go Back</button>
<button type="button" class="btn btn-secondary btn-sm">Try Again</button>
</div>
}
return this.props.children
}
}
export default ErrorHandler;
In the above component, we have used the state variable to display fallback UI. Also we used the `componentDidCatch(error, info)` lifecycle method to handle the error same as the `try/catch`.
To test the above code, we will throw an error from the `<App />` component on page load and that component will be wrapped by the `<Errorhandler />` component in `index.js`.
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import ErrorHandler from './ErrorHandler';
ReactDOM.render(
<errorhandler>
<app>
</app></errorhandler>,
document.getElementById('root'));
App.js
import React, { useEffect } from 'react';
function App() {
// throw an error on page load to test error handling
useEffect(() => {
throw new Error("Something went wrong!");
}, []);
return (
<div class="App">
<h3>Error handling in React - <a href="https://www.cluemediator.com" target="_blank" rel="noopener noreferrer">Clue Mediator</a></h3>
</div>
);
}
export default App;
3. Output
Finally, run the project and see the output as below.
Output - Error handling in React - Clue Mediator
Note: A lot of people are saying that the error handling is not working or the componentDidCatch lifecycle method doesnāt work. But let me clear you that it handles only javascript errors and this will work for child components only there for you can not handle the error of the `<ErrorHandler />` component.