score:5

Accepted answer

the function passed to useeffect is completing successfully. it defines a function, then successfully calls the function. the effect function returns undefined normally, so there is nothing for the error boundary to catch.

error boundaries do not catch all possible errors. specifically, from the documentation on error boundaries:

error boundaries do not catch errors for:

  • event handlers (learn more)
  • asynchronous code (e.g. settimeout or requestanimationframe callbacks)
  • server side rendering
  • errors thrown in the error boundary itself (rather than its children)

if you want the error boundary to take action, then one option is to save the error in state and rethrow it from the component body. for example:

function mycomponent() {
  const [error, seterror] = usestate(null);
  if (error) {
    throw error;
  }

  useeffect(() => {
    // if loading fails, save the error in state so the component throws when it rerenders
    load().catch(err => seterror(err));
  }, []);

  return <div>...</div>
}

score:0

a class component becomes an error boundary if it defines either (or both) of the lifecycle methods static getderivedstatefromerror() or componentdidcatch(). use static getderivedstatefromerror() to render a fallback ui after an error has been thrown. use componentdidcatch() to log error information.

reference: https://reactjs.org/docs/error-boundaries.html

score:2

problem

basically, you have two things working against you. the first is that the cra has an erroroverlay which captures errors first and the second is that since event handlers are asynchronous, they don't trigger the componentdidcatch/getderivedstatefromerror lifecycles: issue #11409.

the work-around is to capture unhandledrejection events on the window.

solution

edit react error boundary promises

code

errorboundary.js

import * as react from "react";

const errorboundary = ({ children }) => {
  const [error, seterror] = react.usestate("");

  const promiserejectionhandler = react.usecallback((event) => {
    seterror(event.reason);
  }, []);

  const reseterror = react.usecallback(() => {
    seterror("");
  }, []);

  react.useeffect(() => {
    window.addeventlistener("unhandledrejection", promiserejectionhandler);

    return () => {
      window.removeeventlistener("unhandledrejection", promiserejectionhandler);
    };
    /* eslint-disable react-hooks/exhaustive-deps */
  }, []);

  return error ? (
    <react.fragment>
      <h1 style={{ color: "red" }}>{error.tostring()}</h1>
      <button type="button" onclick={reseterror}>
        reset
      </button>
    </react.fragment>
  ) : (
    children
  );
};

export default errorboundary;

hello.js

import react, { useeffect } from "react";

export const hello = () => {
  const loader = async () => {
    return promise.reject("api error");
  };

  useeffect(() => {
    const load = async () => {
      try {
        await loader();
      } catch (err) {
        throw err;
      }
    };

    load();
  }, []);

  return <h1>hello world!</h1>;
};

index.js

import react from "react";
import { render } from "react-dom";
import { hello } from "./hello";
import errorboundary from "./errorboundary";

const app = () => (
  <errorboundary>
    <hello />
  </errorboundary>
);

render(<app />, document.getelementbyid("root"));

other thoughts

a cleaner approach would be to just display a pop-up/notification about the error instead of overriding the entire ui. a larger and more complex ui means an unnecessarily large ui repaint:

edit react error ui notification


Related Query

More Query from same tag