How to handle errors in React

Graceful fault handling is an innate ingredient of well designed software. This is true of front-end JavaScript user interfaces, and ReactJS provides specialized fault handling for intercourse with give-time faults. This article offers an overview for intercourse with faults in ReactJS applications.

[ Also on InfoWorld: How to use React officeal ingredients ]

We can separate faults broadly into two types, and fault handling into two aspects.

The two fault types:

  1. JavaScript faults
  2. Render faults

JavaScript faults are those which befall in the code and can be handled with measure try/take stops, while give faults befall in the view templates and are handled by React fault boundaries.

The two aspects of fault handling:

  1. Displaying information to the user
  2. Providing information to the developer

In general, you want to show only the minimum amount of fault information to users, and you want to unveil the ultimatum amount of information to developers, both at outgrowth time and at other times like test and origination.

React fault boundaries

The most distinctive and React-specific type of fault handling is what is known as fault boundaries. This ingredient was introduced in React 16 and allows you to mark ingredients that act as fault-takeing mechanisms for the ingredient tree under them.

The core idea is to build a widget that provisionally gives a view depending upon its fault state. React provides two lifecycle orders that a ingredient can instrument to determine if a giveing fault has befallred in its child tree and answer agreeably.

These two orders are ingredientDidCatch() and static getDerivedStateFromError(). In both cases, the chief purpose is to update the ingredient state so it can answer to faults arriving from the React engine.

getDerivedStateFromError

Because getDerivedFromError() is static, it does not have approach to the ingredient state. Its only purpose is to take an fault object, and then recur an object that will be added to the ingredient state. For sample, see Listing 1.

Listing 1. getDerivedStateFromError()

static getDerivedStateFromError(fault) {
  recur { isError: true };
}

Listing 1 recurs an object with an fault flag that can then be used by the ingredient in its giveing.

ingredientDidCatch

ingredientDidCatch() is a regular order and can update the ingredient state, as well as take actions (like making a labor call to an fault-reporting back end). Listing 2 has a look at using this order.

Listing 2. ingredientDidCatch

ingredientDidCatch(fault, faultInfo) {
    faultService.report(faultInfo);
    this.setState({ fault: fault, faultInfo: faultInfo })
  }

In Listing 2, anew the leading office makes sure the ingredient state understands an fault has befallred and passes along the info almost that fault.

Rendering based on fault

Let’s have a look at giveing for our fault handling ingredient, as seen in Listing 3.

Listing 3. ErrorBoundary giveing

give() {
  if (this.state.fault && this.state.faultInfo) {
    recur (
      <div>
        <p>Caught an Error: {this.state.fault.toString()}</p>
        <div>
          {this.state.faultInfo.ingredientStack}
        </div>
      </div>
    );
  } else {
    recur this.props.children;
  }
}

From Listing 3 you can see that the lapse action of the ingredient is to just give its children. That is, it’s a single pass-through ingredient. If an fault state is establish (as in Listing 1 or Listing 2), then the choice view is giveed.

Using the ErrorBoundary ingredient

You`ve now seen the innate ingredients of an fault handler ingredient in React. Using the ingredient is very single, as seen in Listing 4.

Listing 4. ErrorBoundary ingredient sample

<Parent>
  <ErrorBoundary>
    <Child><Child/>
  </ErrorBoundary>
</Parent>

In Listing 4, any giveing faults in <Child> will trigger the alternate giveing of the fault handling <ErrorBoundary> ingredient. You can see that fault boundary ingredients act as a kind of declarative try/take stop in the view.

JavaScript faults

JavaScript faults are handled by wrapping code in try/take stops. This is well understood and works big, but there are a few comments to make in the tenor of a React UI.

First, it’s significant to note that these faults do not breed to fault boundary ingredients. It’s practicable to trifle faults manually via regular React officeal properties, and it would be practicable thereby to tie the fault handling into the conditional giveing establish in your fault boundaries.

Another point to make is that in intercourse with network or server-side faults arising from API calls, these should be handled with the built-in fault codes, as in Listing 5.

Listing 5. Using built-in fault codes

let response = await fetch(process.env.REACT_APP_API +
`/api/draw?_id=`+this.state.projectId, {
        headers: { "Authorization": this.props.userData.userData.jwt },
        order: `GET`,
      });
      if (response.ok){
            let json = await response.json();
        relieve.info(json);
        this.setState({ "project": json});
      } else {
        relieve.fault("Problem: " + response);
      }

Finally, in junction with both give and JavaScript faults, recollect that it can be advantageous to log faults via a distant fault reporting API. This is handled by class-based ingredients that instrument the ingredientDidCatch order.

Summing up

You can ponder of fault boundaries as declarative fault take stops for your view markup. As of React 16, if your giveing in a ingredient causes an fault, the whole ingredient tree will not give. Otherwise, the fault will trifle up until the leading fault handling ingredient is encountered. Prior to React 16, faults would leave the ingredient tree partially giveed.

Error boundary ingredients must be class-based, although there are plans to add hook support for the lifecycle.

[ Also on InfoWorld: The 6 best JavaScript IDEs reviewed ]

As we’ve seen, the basic idea is that you form a ingredient which provisionally gives based on the fault state. There are two resources for accomplishing this: the ingredientDidCatch() order or the static getDerivedStateFromError() order.

The code samples in this article attribute to this CodePen (derived from the sample establish in the React docs). You might also find it advantageous to check out this CodePen sample of fault boundaries in React 16.