Search code examples
reactjsreact-routerreact-router-redux

Catch API and 401 errors globally in React's router


I use react + react-router + redux. I would like to create a global thing for handling all the errors thrown in the app. Is it possible to catch also API call errors and 401 statuses?

I thoung about something like this in Root.jsx:

window.addEventListener("error", (e) => {});

It works for critical errors which I can log. But what if I want to serve some API errors?

For example: I want to save some grid data, but server thrown an error that 3 of 10 given rows weren't saved (I know it's a common problem and it should be resolved using transactions, but I use Mongo here :P). Now I want to show a simple dialog for a user which displays error message and 3 rows that weren't saved. What if I don't have permissions and the server throws 401 status code? Probably I would like to redirect user to index or login page.

This is some hipothetical example, because I want to simplify the thing I'm currently implementing.

I'm new in React, so I don't know the solutions for now, but if I programmed same thing in Angular, I would use Angular's HTTP Interceptors to solve my problem. I guess I need something similar here (or maybe it's some common solution for this?).

[EDIT]

Hmm. It seems I have found something that solves my problem: fetch-intercept

Anyway, do you know other solutions?


Solution

  • I'm assuming you're using ajax calls to access your API;

    I would create a simple ajax wrapper that looks something like this;

    AjaxWrapper = function(options){
        return $.ajax($.extend({}, options, {
            error: function (jqXHR, textStatus, errorThrown){
                if(jqXHR.status === 401){
                    browserHistory.push('/unauthorized_route_handler');
                }
                options.error(jqXHR, textStatus, errorThrown);
            }
        }))
    }
    

    Then you can simply use this wrapper to call your api, passing in an options object as you normally would to $.ajax. Update the section within the jqXHR === 401 as needed, or add handlers for 403 & 500 as well.