0

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?

1 Answer 1

1

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');
})
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks that was the answer I was looking for.
Can you please post generic jasmine unit test for code above?
To answer my own question if anyone need it use: 'code "use strict"; describe('ErrorInterceptor', function() { var ErrorInterceptor; var httpProviderIt; beforeEach(function() { module('moduleName', function ($httpProvider) { //save our interceptor httpProviderIt = $httpProvider; }); inject(function(ErrorInterceptor) { ErrorInterceptor = ErrorInterceptor; console.log(ErrorInterceptor); }); }); it('should have ErrorInterceptor be defined', function () { expect(ErrorInterceptor).toBeDefined(); }); });'

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.