playerone
playerone

Reputation: 1127

Handle angular http errors using interceptors

My question is what is the best way to handle errors from http REST calls. Should I use interceptors or decorators? My rest functions look something like this:

    queryFunction : function (config) {
    var defer = $q.defer();
    var config = {};
    $http.get(someUrl, config) //or http.put, delete
      .then(function (response) {
        defer.resolve(response.data);
      })
      .catch(function (ex) {
        defer.reject(ex);
      });
    return defer.promise;
    },

How will the simplest interceptor look?

Upvotes: 0

Views: 494

Answers (1)

shershen
shershen

Reputation: 9993

Here's the code for generic $http ErrorInterceptor:

  app.factory('ErrorInterceptor', ['$q', function($q) {
    return {
        responseError: function(rejection) {
            // An error message is shown for all kind of server errors
            if (rejection.status == -1) {
            //alert('Backend is not working');
            //use rejection.data variable 
            }
            return $q.reject(rejection);
         }
     };
   }])

Then it can be included into app config

app.config(['$httpProvider', function($httpProvider) {
  $httpProvider.interceptors.push('ErrorInterceptor');
})

Upvotes: 1

Related Questions