How to use Try/Catch with event Handlers In ReactJS
In React, error boundaries do not catch errors that occur inside event handlers, to catch such errors we use the regular JavaScript try/catch block with event handlers.
Syntax:
try {
changeButton();
}
catch (error) {
// Error Handler code
}
Example: The below code implements the try/catch block with event handlers to handle errors in react components.
// App.js
import React, { Component } from "react";
export class MyComponent extends Component {
constructor(props) {
super(props);
this.state = { error: null };
this.handleButton = this.
handleButton.bind(this);
}
handleButton() {
try {
throw new Error
("Something bad happened!");
} catch (error) {
this.setState({ error });
console.log(error.message)
}
}
render() {
if (this.state.error) {
return <div>
<h1>
Caught an error.
</h1>
</div>
}
return <div>
<h2>
Click the below button to
<br /> catch the error.
</h2>
<button onClick={this.handleButton}>
Click Me
</button>
</div>
}
}
export default MyComponent;
Output:
How does React Handle Errors in the Component Tree ?
In the older versions of React (before v16), we do not have any feature to handle the React errors which were occurred in the components and these errors are used to corrupt the internal state of the React component.
Below are the methods to handle errors in the React component tree:
Table of Content
- Using Error Boundaries
- Using Try/Catch with event Handlers
Contact Us