- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Error boundary in React.js
The error boundary mechanism helps to show meaningful error message to user on production instead of showing any programming language error.
Create a react class component
import React, {Component} from 'react'; class ErrorBoundary extends Component{ state={ isErrorOccured:false, errorMessage:'' } componentDidCatch=(error,info)=>{ this.setState({isErrorOccured:true,errorMessage:error}); } render(){ if(this.state.isErrorOccured){ return <p>Something went wrong</p> }else{ return <div>{this.props.children}</div> } } } export default ErrorBoundary;
We have a state object having two variables isErrorOccured and errorMessage which will be updated to true if any error occurs.
We have used a React life cycle method componentDidCatch which receives two arguments error and info related to it.
In the render method of ErrorBoundary class we are checking if any error is set we are displaying a simple error saying ‘Something went wrong’
If no errors set we are just returning the prop children
How to use error boundary
<ErrorBoundary> <User/> </ErrorBoundary>
We are wrapping the child component where there is possibility of error occurring inside error boundary like above.
Please note that this error boundary approach only works in production mode of build. In development mode it simply displays the actual error on browser instead of these custom errors.
Use of Error Boundary on production helps to show user meaningful error message on screen instead of displaying some technical code errors.
- Related Articles
- SVG morphing in React JS
- Adding Lottie animation in React JS
- SVG drawing in React JS frontend
- Debugging and Error Boundary in React.js
- Creating a Particle Animation in React JS
- Creating a Customizable Modal in React JS
- Creating animated loading skeletons in React JS
- Drawing arrows between DOM elements in React JS using react-archer
- Creating an Airbnb Rheostat Slider in React JS
- Creating a Rich Text Editor in React JS
- Device Detection and Responsive Design in React JS
- Using pointer light for better lighting in React JS with React-Three-Fiber
- SVG zoom-in and zoom-out in React JS
- How to make a resizable element in React JS
- Making a timer in React JS using reactspring animation
