How To Correctly Handle Errors In React With Error Boundary

How To Correctly Handle Errors In React With Error Boundary

ยท

5 min read

Hi everyone, As we build applications, errors are inevitable, we use different ways to handle them, but there will always be some edge cases that you did not consider, thus during production user will get a blank screen because of such error which is not good for user experience because the end user may not know what to do in that situation.

That's why we need to handle them. In this blog, I will give you a demo of how you can handle such errors in your application. I will use Sandbox for the code, So without any further ado, let's dive in.

  • install react-error-boundary

      # npm
      npm install react-error-boundary
    
      # yarn
      yarn add react-error-boundary
    
  • Here we will implement an Error boundary for the whole app so we will wrap the whole app with ErrorBoundary.

import { StrictMode } from "react";
import { createRoot } from "react-dom/client";

// import ๐Ÿ‘‡๐Ÿ‘‡ Error boundary
import { ErrorBoundary } from "react-error-boundary";
import App from "./App";
const rootElement = document.getElementById("root");
const root = createRoot(rootElement);


// wrap whole app with Error boundary ๐Ÿ‘‡๐Ÿ‘‡ 
root.render(
  <StrictMode>
    <ErrorBoundary fallback={<div>Something went wrong</div>}>
      <App />
    </ErrorBoundary>
  </StrictMode>
);

So what happened exactly with this snippet?

First of all, we import the Errorboundary component and also wrap the whole app with this. it also has a fallback as a prop, so when the error appears. instead of showing a blank screen application will show the text 'Something went wrong' so that users can know there is an error.

  • let's make an error and see if it works.

      export default function App() {
        // const users = ["john", "sam"];
        const users = {};
    
        return (
          <div className="App">
            {users.map(function (user) {
              return <p>{user}</p>;
            })}
          </div>
        );
      }
    

    So what happened exactly with this snippet?

    This is simple here we are showing the array of users on the screen, but due to any reason, we are getting an object instead of an array. an error can come due to any unexpected situation. let me elaborate more about this.

    Error Boundaries are only designed for intercepting errors that originate from 3 places in a React component:

    • During render phase

    • In a lifecycle method

    • In the constructor

As a counterpoint, these are the places where Error Boundaries will not be able to catch an error:

  • Event handlers (e.g., onClick, onChange, etc.)

  • setTimeout or requestAnimationFramecallbacks

  • Server-side rendering (SSR)

  • And errors caused by the error boundary itself (rather than its children).

  • Run the app and you can see we handle the error perfectly.

  • Suppose you want to display a component instead of just text. You can do that too. You need to use FallbackComponent as a prop and passed your component. Here is an example-

// /components/Errorpage
function ErrorPage({ error }) {
  console.log("error" + error);
  return (
    <div>
      <p>Something went wrong:</p>
      <pre style={{ color: "red" }}>{error.message}</pre>
    </div>
  );
}

export default ErrorPage;

So what happened exactly with this snippet?

The above is the error page component that we will pass in the Fallback component. Here we are using an error object to display an error message inside our component. Now we need to update our props inside the error boundary component.

import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { ErrorBoundary } from "react-error-boundary";
import App from "./App";
import ErrorPage from "./components/ErrorPage";
const rootElement = document.getElementById("root");
const root = createRoot(rootElement);

root.render(
  <StrictMode>
   //Here we update our props and pass our component
    <ErrorBoundary FallbackComponent={ErrorPage}>
      <App />
    </ErrorBoundary>
  </StrictMode>
);
  • Now we run the app again. it gives us an error message.

  • Now let's learn about some more things. we have two more important props. one for resetting the state of your app so the error doesn't happen again. you can give a button on the error screen so that you can navigate the user to the home page or any page you want and also remove any errors that were there before the error.

  • Other props for doing something with the error, such as logging the error.

  • Let me give a sample code for these two scenarios

  • I need to modify the code I am assuming, you know routing in react.

      //update the app.js
      import "./styles.css";
      import { BrowserRouter, Routes, Route, Link } from "react-router-dom";
    
      // Home component
      const Home = () => {
        return (
          <div className="App">
            <h1>My home</h1>
            <Link to="/user">Go to user</Link>
          </div>
        );
      };
    
      // user component
      const User = () => {
        // const users = ["john", "sam"];
        const users = {};
        return (
          <div className="App">
            {users.map(function (user) {
              return <p>{user}</p>;
            })}
          </div>
        );
      };
    
      export default function App() {
        return (
        //routing 
          <BrowserRouter>
            <Routes>
              <Route path="/" element={<Home />} />
              <Route path="/user" element={<User />} />
            </Routes>
          </BrowserRouter>
        );
      }
    

    So what happened exactly with this snippet?

    We made two components Home and User in app.js itself for your simple understanding. I made this because I need to demonstrate once we click onReset. it will reset the state and error and navigate to the home page or whatever page you want to navigate.

  • Update index.js.


import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { ErrorBoundary } from "react-error-boundary";
import App from "./App";
import ErrorPage from "./components/ErrorPage";
const rootElement = document.getElementById("root");
const root = createRoot(rootElement);


const logError = (error) => {
  console.log("log error" + error);
};


root.render(
  <StrictMode>
    <ErrorBoundary
      FallbackComponent={ErrorPage}
      onError={logError}
      onReset={() => (location.href = "/")}
    >
      <App />
    </ErrorBoundary>
  </StrictMode>
);
  • Run the app.

  • Click on go to user button.

  • As soon as the error appears, logError gets executed.

  • click on the Try Again button.

  • you can see we return to the home page.

And that wraps up our blog! I hope this article has given you a clear understanding of how to handle errors in React with Error Boundary.

Thank you for investing your time in reading this blog. I sincerely hope that the information provided here proves helpful and empowers you on your coding journey. Wishing you a future filled with success, happiness, and enjoyable coding experiences! Happy coding! ๐Ÿ˜Š

ย