5

I have a Create React App (that uses react-router v6) that is setup the following way to communicate with the API.

At the top level - I wrapped my app in an ErrorBoundary (Sentry.ErrorBoundary).

When fetching the API, the front-end calls a useQuery method from react-query (which uses an axios instance to fetch the requested API URL).

But how do I handle an error 404 or 500 from axios?

Currently the ErrorBoundary renders an ErrorPage that is blocking the UI. I'm trying to find a better way that don't block the UI.

The way I see it, I can handle errors in the following way:

  1. using axios interceptor directly - but currently it's in a separate file and don't use useNavigate() of React Router - so either I use window to redirect to /404 or /500 or I wrap it inside a React.Context (itself wrapped in my React Router context) so that it can use useNavigate() inside of it from react-router to redirect to /404 or /500.

  2. using onError handler from react-query (directly inside my QueryClient config) that will be passed an AxiosError and redirect to /404 or /500 based on axios error response status

  3. Using the error object that comes from Sentry.ErrorBoundary and render a different UI based on the error response status from axios

Solution 1 and 2 will leverage useNavigate() by react-router to redirect (or window.pathname) but I'm not satisfied with these... The solution 3 is more interesting for me (as I can have a 404 UI without changing pathname!) but the solution 3 does not handle the error (it'll be uncaught)...

Any recommendation or better idea?

I haven't found that much regarding handling errors in an SPA - thank you for your time :)

feyndev
  • 122
  • 5

0 Answers0