React Error Boundaries

React Error Boundaries

In the past, the errors of JavaScript within the components were used to corrupt the internal state of react and cause it to emit the cryptic errors on the next renders. These errors were always because of a previous error in the application code, but there was not any way in react to handle them gracefully in components, and also we could not recover them.

React 16 introduces the new concept of handling the errors is by Error Boundaries. Error boundaries are the components of react that catch the errors of JavaScript anywhere in their child component tree, log those errors, and will display a fallback UI rather than the component tree that crashed.

Error boundaries catch errors during rendering, within lifecycle methods, and in the constructors of the whole tree below them.

Error boundaries do not catch the errors for Event handlers, Asynchronous code, server-side rendering, errors thrown in the error boundary itself.

For a simple application of react, you can declare the error boundary once and can use it for the complete application. For complex applications having multiple components, you can declare multiple error boundaries to recover every part of the entire application.

Error Boundary in class

A class will be an error boundary if it defines both of the lifecycle methods static getDerivedStateFromError() or componentDidCatch(). The use of static getDerivedStateFromError() is for rendering a fallback UI after an error has been thrown. The use of componentDidCatch() is for logging the error information.

For the components, Error boundaries work as a catch {} block of JavaScript. Only the class components can be error boundaries. An error boundary cannot catch the error within itself. If the error boundary fails in the rendering of an error message, then the error will propagate to the nearest error boundary above it. This is also similar to how the catch {} block works in JavaScript.

Implementation of Error Boundaries

Let us try to understand the implementation of error boundaries by using the following example:

class ErrorBoundaryExample extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
// Update the state so the next render show the fallback UI.
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
// We can also log the error for an error reporting service
logErrorToMyService(error, errorInfo);
}
render() {
if (this.state.hasError) {
// You can render any custom fallback UI 
return <div>Something went wrong.</div>;
}
return this.props.children; 
}
} 

Now, you can use it as a regular component. Add the new component in HTML, which you require to add in the error boundary. In this example, we are adding a Widget component.

  
  

Where to Place Error Boundaries

The error boundary entirely depends on you. You can use the error-boundaries at the top-level of the application components or wrap it on the individual components for protecting them from the breaking of other parts of the application.

Example of using Error-boundary:

Let us see an example of it:

App.js

import React, { Component } from 'react';
import './App.css';
import Actors from './Actors';
class App extends Component {
render() {
return (

Actors Performing at Tonight in the show

); } } export default App;

Actors.js

import React from 'react';
function Actors({actorName}) {
if (actorName === 'Govinda') {
throw new Error ('not performing tonight!')
}
return (
{actorName}
) } export default Actors;

Output:

Actor Performing tonight show

If you change one of the artist names to 'Govinda’ like <Actors actorName='Govinda'></Actors> then you will see the following:

Where to Place Error Boundaries

New Behavior for uncaught errors

If the error doesn't catch by any error boundary, it will result in the unmounting of the complete React application. It is the new implication in the error boundaries.

Error Boundaries inside Event Handlers

As stated above, error boundaries do not catch the errors in event handlers. React does not require any error boundary to recover from errors inside event handlers.

If you have to catch the error within the event handler, you should use the regular JavaScript try/catch statement as shown in the following example:

class App extends React.Component {
constructor(props) {
super(props);
this.state = { error: null };
this.handleClick = this.handleClick.bind(this);
}
handleClick() { 
try {
// Do something that can throw the error
} catch (error) {
this.setState({ error });
}
}
render() {
if (this.state.error) {
return 

Caught an error.

} return
Click Me
} }

It is to be noted that the above example is demonstrating the behavior of regular JavaScript and does not use the error boundaries.



ADVERTISEMENT
ADVERTISEMENT