Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle error thrown by React.lazy component?

I hava a function that load component dynamiclly below:

export const loader = (file: string) => {
  let pagePath = file.replace(/^views/, 'pages');
  pagePath = pagePath.replace(/\/index$/, '');

  const LazyComponent = lazy(
    () =>
      import(
        /* webpackChunkName: "dynamic_page" */ `@/${pagePath}/index.tsx`
      ),
  );

  return (
    <Suspense fallback={<Loading />}>
      <LazyComponent />
    </Suspense>
  );
};

export const Loader: React.FC<{ path: string }> = ({ path }) => {
  return (
    <ErrorBoundary>
      {loader(path)}
    </ErrorBoundary>
  );
};

When passed wrong path, dynamic import part throw error:

caught Error: Cannot find module './pages/modules/info/priceConfig/index.tsx'

Why is the error not handled by ErrorBoundary component? And if I want to catch it and return a default component, how?

like image 975
acui145 Avatar asked Sep 15 '25 22:09

acui145


1 Answers

Why is the error not handled by ErrorBoundary component?

The ErrorBoundary handles errors thrown within the React component tree during rendering, lifecycle methods. It does not catch errors thrown within asynchronous code, such as Promises.

A workaround was suggested here: https://eddiewould.com/2021/28/28/handling-rejected-promises-error-boundary-react/

Solution for your problem:

const LazyComponent = lazy(() =>
    import...).catch(
      (error) => {
        console.error("Component Failed Loading:", error);
        return { default: FallbackComponent };
      }
    )
  );
like image 98
Confront Avatar answered Sep 18 '25 15:09

Confront