Catching 403 errors in angular and showing popup

On our site, I find myself in this predicament where you basically transfer a project to another user. When that happens, if the original user tries to view a project they just uploaded, we give back 403 because they are no longer the owner of the project. I started looking for interceptors in angular. I hooked up a responseError just to see if it was caused by a call to 403, for example

.config(($httpProvider) => {
        $httpProvider.interceptors.push(function() {
            return {
                responseError: function(rejection) {
                    console.log("bad response");
                    return rejection;
                }
            }
        });
    });

      

So my "bad answer" gets called and that's it, but I wasn't sure how I can show a modal view or something in this place that shows an error to the user, since this 403 response actually happens on several of our different resources, not just projects. Any thoughts? Thank you in advance.

+3


source to share


1 answer


If I understand correctly, you only want to show the error dialog for some HTTP calls, not for every call going through your interceptor. You could probably try this: -

Set up the config for your HTTP calls, say handleError:true

.

$http.get('myurl', {handleError:true})....


$http.post('myurl',data, {handleError:true})....

      

etc..

and in your interceptor find this config setting to display the error: -



   $httpProvider.interceptors.push(function() {
        return {
            responseError: function(rejection) {
                console.log("bad response");
                if(rejection.config.handleError && rejection.status === 403){
                    //show error dialog
                }
                return rejection;
            }
        }
    });

      

You can also send a status code that needs to be handled as well.

 $http.get('myurl', {handleStatus:[403,...]})....

      

and

  $httpProvider.interceptors.push(function() {
        return {
            responseError: function(rejection) {
                if((rejection.config.handleStatus || []).indexOf(rejection.status) > -1){
                    //show error dialog. probably you could show it in a $timeout to make this async.
                }
                return rejection;
            }
        }
    });

      

+7


source







All Articles