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:
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
/404or/500or I wrap it inside aReact.Context(itself wrapped in my React Router context) so that it can useuseNavigate()inside of it fromreact-routerto redirect to/404or/500.using
onErrorhandler from react-query (directly inside myQueryClientconfig) that will be passed anAxiosErrorand redirect to/404or/500based on axios error response statusUsing the error object that comes from
Sentry.ErrorBoundaryand 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 :)