frontarm / navi

🧭 Declarative, asynchronous routing for React.
https://frontarm.com/navi/
MIT License
2.07k stars 71 forks source link

Catch getView exception #176

Closed Menci closed 3 years ago

Menci commented 4 years ago

I want to throw exceptions from getView on data fetching errors. Such as the user entered an invalid ID or doesn't have the permission. They are recoverable error of the current view, not application bugs so I think ErrorBoundary is not suitable. How can I catch them in navi and display an error page for users?

jamesknelson commented 4 years ago

One option would be to use try/catch and then emit the errors via the route's data property, or pass them to a prop on the view element.

Menci commented 4 years ago

I just don't want to wrap every getView with try/catch.

My current solution is wrap with a custom function:

export function defineRoute(getViewFunction: Resolvable<React.ReactNode>) {
  return route({
    async getView() {
      try {
        return await getViewFunction.apply(this, arguments);
      } catch (e) {
        if (e instanceof RouteError) return <ErrorPage {...e} />;

        if (!(e instanceof Error)) e = new Error(String(e));
        return <ErrorPage uncaughtError={e} message={null} options={null} />;
      }
    }
  });
}