Sam
Sam

Reputation: 15761

AngularJS - Handling $http errors?

I have a directive that I am injecting a service into that makes $http calls to a back end service.

How do you handle 404/401/HTTP errors in general? I am looking for a best practice pattern.

Does $http gobble up and reject the promise when it hits a HTTP error?

This is what I have so far, and it seems to work OK, but I am not sure I am doing the recommended way:

Service

app.service('helpService', ['$http', function ($http) {
    return {
        getHelpUrl: function (pageUrl) {
            return $http.post('Home/GetHelpUrl', { pageUrl: pageUrl });
        }
    }
}]);

Directive

app.directive('helpLink', ['$location', 'helpService', function ($location, helpService) {
    return {
        restrict: 'A',
        replace: true,
        scope: {},
        template: function (elem, attrs) {
            return '<a ng-href="{{helpUrl}}" ng-show="showLink" target="_blank">Help?</a>';
        },
        link: function (scope, elem, attrs) {
            scope.showLink = false;

            helpService.getHelpUrl($location.path()).success(function (data) {
                scope.helpUrl = data.helpUrl;
                scope.showLink = true;
            });
        }
    }
}]);

Upvotes: 0

Views: 1689

Answers (2)

Chandermani
Chandermani

Reputation: 42669

Like the success method there is also a error(function(data, status, headers, config) method defined over $http.

This is example from the documentation

$http({method: 'GET', url: '/someUrl'}).
  success(function(data, status, headers, config) {
    // this callback will be called asynchronously
    // when the response is available
  }).
  error(function(data, status, headers, config) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });

You can use it to catch errors

Upvotes: 1

calebboyd
calebboyd

Reputation: 5753

If you are wanting to capture all the errors You might look in to Interceptors. Have a look at the documentation. You could also use the error callback in your .then method. (this would replace your .success method) since $http returns a promise (see $q promise api):

The interceptor could be registered something like:

app.config(function($httpProvider){
    $httpProvider.interceptors.push('connectionInterceptor');
});

app.factory('connectionInterceptor', function ($q) {
    return {
        'requestError':function(rejection){
             //do something general (global)
             //send a rejection
        },
        'responseError': function (response) {
             //do something general (global)
             //send a rejection
        }
    };
});

Upvotes: 1

Related Questions