Exploit React Error Boundaries to Improve UX
Tags: programming, createreactapp, react, softwaredevelopment
Published: 2018-12-28 17:11:00

---
title: Exploit React Error Boundaries to Improve UX
published: true
tags: programming,create-react-app,react,software-development
canonical_url: 
---

#### How to Automate Error Detection & Reporting

![](https://cdn-images-1.medium.com/max/1024/1*zvJpnhdbkKSjqYdFKmSDCg.jpeg)<figcaption>From Pexels.com</figcaption>

[User Experience](https://www.interaction-design.org/literature/topics/ux-design) (UX) is a broad and deeply complex discipline that is recognized by most in the development community as being integral to the success of an application. However, one aspect of UX that doesn’t get the attention it deserves in most applications centers around [error detection and reporting](http://architectingusability.com/2012/06/05/designing-error-handling-for-maximum-usability-in-your-application/).

Too many applications take a casual approach to error detection, handling, and reporting because developers view it as either drudgery or unimportant. It’s not just developers who are at fault. It is often the case that [Product Managers](https://en.wikipedia.org/wiki/Product_manager) prioritize new features over items like error handling and recovery that are viewed as mundane.

However, there are compelling reasons for giving attention not just to how application failures are detected and handled, but the UX considerations governing how they impact the user.

1. Users expect applications to work - not to fail. In general, users tend to remember the failures and their impact more than the successes they achieve from the application. What will your users remember if they have to follow a procedure like [this](https://docs.acquia.com/support/tickets/) to report every issue?
2. The [best applications](https://savvyapps.com/blog/what-makes-a-great-app) are those that are invisible to the user. The goal is to not get in the way of getting work done rather than having to deal with the mechanics of using the application.
3. [“Perception is reality](https://www.elitedaily.com/life/motivation/perception-is-reality).” How users perceive an application depends on the framing of information, events, and results. Sometimes developers are their own worst enemies when it comes to things like error messages. For example, “A catastrophic error has occurred! Open a ticket…” as opposed to “We’re unable to process your request at this time. For more information see…”.
4. [Software architecture](https://www.ou.nl/documents/40554/349790/IM0203_01.pdf) is as much a feature as any application functionality supporting a particular business process. Anything that supports the applications ability to add value to the user should be considered as a feature.

There are a number of techniques and tools that can be used to make error detection and handling more transparent to the user and to improve the speed and quality of developer response. These include,

- Designing and implementing an overall error detection and handling strategy
- Crafting messages that are easy to understand and which are actionable
- Logging pertinent application data and user activity
- Automating recovery
- Automating screenshots for diagnostic purposes
- Automatically creating issue tickets for when errors are encountered

The remainder of this article will focus on two of these — implementing an application-wide error detection strategy and automatically creating issue tickets. We’ll be demonstrating these using the [feature/06-error-handling](https://github.com/jdmedlock/meteorite/tree/feature/06-error-handling) and the [feature/07-create-issue](https://github.com/jdmedlock/meteorite/tree/feature/07-create-issue)branches in the Meteorite Explorer repo on GitHub.

### Implementing an Error Detection & Handling Strategy

![](https://cdn-images-1.medium.com/max/1024/1*hEbJvltnslRrdEzjWQ7Img.jpeg)<figcaption>Photo by <a href="https://unsplash.com/photos/XJXWbfSo2f0?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Luca Bravo</a> on <a href="https://unsplash.com/search/photos/programming?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption>

Implementing an error handling strategy seems quite simple. We’ll start by wrapping the highest level React component in a `try...catch` statement to intercept any errors.

{% gist https://gist.github.com/jdmedlock/e81d066276e85ab39bf05d53f12cad7d %}

To test we’ll throw a new Error in Search.js when the user clicks on the ‘Search’ button. Testing this we see the error message ‘Unknown error intercepted…’ in the console. But wait! That’s not what is displayed. It looks as though the error didn’t percolate up to the `try...catch` statement in `index.js`.

![](https://cdn-images-1.medium.com/max/1024/1*gBEUKmoVyFz7ck1bkNi6rg.png)<figcaption>Figure 2 — Unexpected Error results</figcaption>

In the stack trace we can see the error was intercepted, but not by the applications `index.js` routine. Instead, it was detected by `development.js` in the `react-dom` library and stopped there.

So, now we have a dilemma. How can our application code implement additional logging or automated recovery if it can’t get control when an error occurs?

#### React Error Boundary

Luckily, the Error Boundary feature was introduced in React 16. Error boundaries are components that intercept errors thrown during the rendering process, from within lifecycle methods, and inside constructors in the entire tree they encapsulate.

{% gist https://gist.github.com/jdmedlock/70276ccd81020a329f9df4365d8521f5 %}

Figures 3 and 4 show the `GlobalErrorBoundary` created for Meteorite Explorer and its use within `App.js`. Notice that since this error boundary component is being used to intercept errors across the application, and as such it brackets all components. The result is it will receive control for error occurring anywhere within the component hierarchy.

{% gist https://gist.github.com/jdmedlock/4c7582962a47ef44334057c4f94726dd %}

Executing the application after adding `GlobalErrorBoundary.js` will display the message “Meteorite Explorer encountered an error! Oh My!”. But once again the reality doesn’t match our expectations (see Figure 5, below).

![](https://cdn-images-1.medium.com/max/1024/1*DZU08689BRYVujIfh0ImUg.png)<figcaption>Figure 5 — Why don’t we see the custom message from GlobalErrorBoundary.js?</figcaption>

The reason the expected message isn’t displaying is that the Meteorite Explorer application has been generated using C[reate React App](https://reactjs.org/docs/create-a-new-react-app.html#create-react-app), which injects its own [error overlay](https://github.com/facebook/create-react-app/issues/3627) into applications running in development mode. Any of the following three alternatives may be used to suppress this overlay,

1. Run in production mode
2. Click the ‘X’ in the upper right-hand corner of the overlay to dismiss it (see Figure 6)
3. Use Chrome DevTools to remove the `error` and `unhandledrejection` event listeners

![](https://cdn-images-1.medium.com/max/1024/1*MkU9OAJeai84YvhEi3v-1Q.png)<figcaption>Figure 6 — Custom error message from GlobalErrorBoundary.js after dismissing the error overlay</figcaption>

As useful as Error Boundaries are they do have a few limitations. They cannot intercept errors originating in,

- Event handlers
- Asynchronous code (e.g., callbacks)
- Server-side rendering (SSR)
- Errors generated from within the error boundary itself

#### The Case for Multiple Error Boundaries

Although globally intercepting errors is one option, it’s even more valuable to set error boundaries around specific components (see Figure 7). Just like `try...catch` statements, error boundaries can be used to improve error message quality by providing information specific to each situation and to tailor automatic recovery accordingly.

![](https://cdn-images-1.medium.com/max/782/1*kBeRwa6FkWVUFKQegYJLVQ.png)<figcaption>Figure 7 — Multiple Error Boundaries</figcaption>

To demonstrate, the `Search.js` component has been updated to generate an error if the user attempts to search on a prohibited word (see Figure 8) and the search components have been placed in their own Error Boundary. Errors trapped by specific error boundaries such as this do not percolate to higher error boundaries, even though they may be nested. However, it’s still a good practice to use a global error boundary to catch any errors outside the scope of an error boundary at a lower level.

{% gist https://gist.github.com/jdmedlock/08188f844a2120a2b6d359a9f923cea5 %}

When a prohibited word is detected not only will an error be thrown, but the `SearchErrorBoundary` component will also create a customized message displaying the specific word that triggered the error (see Figure 9).

![](https://cdn-images-1.medium.com/max/1024/1*ZvCuUh0QEicV2N5jRO1uFg.png)<figcaption>Figure 9 — Trapping errors in the Search Component</figcaption>

### Automating Issue Ticket Creation

![](https://cdn-images-1.medium.com/max/1024/1*i384H_6SMsFYMMH4aPrZfw.jpeg)<figcaption>Photo by <a href="https://unsplash.com/photos/U3sOwViXhkY?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Franck V.</a> on <a href="https://unsplash.com/search/photos/automation?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption>

The examples in the previous section were created to demonstrate the basic functionality of a React error boundary. They are, however, not very practical since they trap a particular condition and generate a custom error message. If this is all that is required, it can be better accomplished using more straightforward techniques.

Intercepting errors, gathering information defining the state of the application at the time it occurred, and automatically opening a support ticket is a feature valuable to both users and developers. For users, it removes the burden of manually creating a new ticket, and for developers, it improves the type and quality of information needed to resolve the problem.

To show how this might be accomplished using React Error Boundaries the `componentDidCatch` function in `SearchErrorBoundary.js` has been updated to create a new issue ticket from the data available at the time the error was detected. This includes props containing the current search term that triggered the error. A new GitHub issue is created by the call to `createIssue()`, and a JSON string representing the issue is returned and added to `SearchErrorBoundary`'s state.

The render function generates a customized error message including the link to the new issue in the Meteorite Explorer repo on GitHub.

{% gist https://gist.github.com/jdmedlock/25003c6766404ca432b6d8bffc431286 %}

The createIssue utility function relies on the [GitHub Create Issue](https://www.npmjs.com/package/github-create-issue) package to create new issues. This package uses the [GitHub REST API V3](https://developer.github.com/v3/) and was selected because although GitHub’s [GraphQL API V4](https://developer.github.com/v4/) supports the creation of issues, it is currently in preview mode and subject to change at any time.

The `formatGHIssue` function creates a [Markdown formatted](https://help.github.com/articles/basic-writing-and-formatting-syntax/) issue body and uses the GitHub Create Issue package to create a new issue. Upon completion, the JSON representation of the new issue is returned to the caller.

{% gist https://gist.github.com/jdmedlock/7d1cabe2dd33c1e446daf321de878be8 %}

The `formatGHIssue` function creates an issue body containing information helpful to the developer such as the identity of the user who experienced the error, environmental data such as the client platform, the error message, and the stack trace. Also, it also adds a label identifying the issue as being a bug.

{% gist https://gist.github.com/jdmedlock/947063dd5151f077ea8a49dc6c0ad06e %}

With these changes in place, when an error is intercepted an issue reporting the error is created in GitHub (see Figure 13) and a customized error message is displayed (see Figure 14).

![](https://cdn-images-1.medium.com/max/1024/1*SARPnbFH6pLIZjBXZjohfQ.png)<figcaption>Figure 13 — Custom Error Message including a link to autogenerated Issue</figcaption>

![](https://cdn-images-1.medium.com/max/837/1*4U0ytiaa4jBgbKm01x1h9Q.png)<figcaption>Figure 14 — Body of Automate Generated Issue</figcaption>

#### Making it Production-Ready

As useful as this may seem it’s not production-ready. It’s merely a demonstration of how React Error Boundaries can be used to create a useful application feature. A few additional items to consider to make it production-ready are,

- Limiting the number of issues automatically generated in a predefined time frame to prevent duplicates and flooding the ticketing system.
- Searching for existing issues before creating a new one.
- Ensuring that errors in the issue creation logic don’t result in a recursive loop.
- Adding user profile data to the ticket as long as it doesn’t contain personal identifying or confidential information.
- Allowing the user to provide supplemental information as part of an automatically created ticket. For example, the steps to recreate the problem.
- Your organization may dictate a ticketing system such as [ServiceNow](https://www.servicenow.com/), [Remedy](http://www.bmc.com/it-solutions/remedy-service-desk.html), [Bugzilla](https://www.bugzilla.org/), or [Jira](https://www.atlassian.com/software/jira) rather than GitHub.
- Since different Error Boundary handlers have a lot in common an opportunity exists to create a generic handler that’s customized using props and state.

### Guarding Application Secrets

It’s worth noting that to keep client secrets, like Meteorite Explorer’s GitHub access token, confidential they are defined as environment variables in the `.env` file. This file is added to `.gitignore` so it won't be uploaded to the public GitHub repo where it would be visible to anyone.

In applications created by Create React App, these environment variables are required to be prefixed by `REACT_APP_`. These can be accessed within application code using variables such as `process.env.REACT_APP_GITHUB_ACCESS_TOKEN`.

![](https://cdn-images-1.medium.com/max/815/1*dzGdtF7BmntZLMXCwz3G-Q.png)<figcaption>Figure 15 — .env File</figcaption>

### Wrapping It Up

![](https://cdn-images-1.medium.com/max/1024/1*Uwbv9Nzv7uoZV_hJwrsPGQ.jpeg)<figcaption>Photo by <a href="https://unsplash.com/photos/cnseVhmbA7k?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">rawpixel</a> on <a href="https://unsplash.com/search/photos/conclusion?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption>

Creating leading-edge applications is a very complex and demanding task. As organizations mature their core processes often increase in sophistication which requires the use of equally sophisticated applications. Although domain-specific features are important, sometimes the largest gains in user satisfaction come from correcting seemingly small issues and adding functionality to help make the application “invisible”.

> “The difference between something good and something great is attention to detail.” … Charles R. Swindoll

Sometimes the best path to success comes from taking the time to listen to users, observe how they use the applications they depend on, paying attention to improving mundane and repetitive tasks, and eliminating even the smallest of obstacles to productivity. In application development attention to even the smallest of details matters.

* * *