0

Is it possible to catch errors like 502 Proxy Error in the $http service from Angular1? Normally the server is returning some HTTP status code like 500 and in the body an error message.

Errors like this are exactly the same of course, it's an 502 error and the body is some HTML code (default apache), so I get that HTML code as error message and my application wil show that code as error.

Is there a way to catch those errors and rewrite them to user friendly error messages?

2
  • Of course. Did you try catch/error callback? Commented Jun 21, 2018 at 11:31
  • @dfsq sure. We are using the promise which is returning from the service like then(function(response){console.log(response)}).catch(function(reason){ console.error(reason) //showError();}) Commented Jun 21, 2018 at 11:34

1 Answer 1

1

For this you can use your own httpInterceptor kinda like this:

app.config(['$httpProvider', function($httpProvider){
    $httpProvider.interceptors.push('myhttpInterceptor');
}]);
app.factory('myhttpInterceptor', ['$q', '$injector', function($q, $injector){
    return {
        // optional method
        'request': function(config) {
            // do something on success
            return config;
        },

        // optional method
        'requestError': function(rejection) {
            // do something on error
            if (canRecover(rejection)) {
                return responseOrNewPromise
            }
            return $q.reject(rejection);
        },

        // optional method
        'response': function(response) {
            // do something on success
            return response;
        },

        // optional method
        'responseError': function(rejection) {

            // do something on error
            if (canRecover(rejection)) {
                return responseOrNewPromise
            }
            return $q.reject(rejection);
        }
    };
}]);
Sign up to request clarification or add additional context in comments.

1 Comment

Nice, this was I need! Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.