67

How can I handle an HTTP error, e.g. 500, when using the AngularJS "http get then" construct (promises)?

$http.get(url).then(
    function(response) {
        console.log('get',response)
    }
)

Problem is, for any non 200 HTTP response, the inner function is not called.

laurent
  • 88,262
  • 77
  • 290
  • 428
Federico Elles
  • 4,659
  • 7
  • 27
  • 35

6 Answers6

148

You need to add an additional parameter:

$http.get(url).then(
    function(response) {
        console.log('get',response)
    },
    function(data) {
        // Handle error here
    })
laurent
  • 88,262
  • 77
  • 290
  • 428
  • 11
    Note also that 'response' object above has: data, status, headers, config, statusText. The 'data' object above has: data, status, config, statusText. (There are special rules about whether statusText is passed - browsers, mobile or not, web server etc.) – OzBob Apr 13 '15 at 04:43
  • Also note: `data.config.url` contains the full **url + params** , in case you passed params next to url – Christophe Roussy May 24 '17 at 13:21
  • I don't know but it is not working for my case. Always the response code is executed. – rahim.nagori May 01 '19 at 13:15
58

You can make this bit more cleaner by using:

$http.get(url)
    .then(function (response) {
        console.log('get',response)
    })
    .catch(function (data) {
        // Handle error here
    });

Similar to @this.lau_ answer, different approach.

Ravish
  • 2,383
  • 4
  • 37
  • 55
14

https://docs.angularjs.org/api/ng/service/$http

$http.get(url).success(successCallback).error(errorCallback);

Replace successCallback and errorCallback with your functions.

Edit: Laurent's answer is more correct considering he is using then. Yet I'm leaving this here as an alternative for the folks who will visit this question.

Dan Atkinson
  • 11,391
  • 14
  • 81
  • 114
Umur Kontacı
  • 35,403
  • 8
  • 73
  • 96
  • 11
    It is worth mentioning that this does not do the same thing as Laurent's answer. `.then()` returns a promise. `.success()` and `.error()` do not. – James Brewer Nov 11 '14 at 11:11
  • 5
    @james-brewer: To be more accurate, `.then()` returns a **new** promise. `.success()` and `.error()` do not, they both return the original promise provided by `get(url)`. – dod Jan 19 '15 at 14:59
  • 10
    It's important also to keep in mind that `success` and `error` callbacks for $http api will be deprecated. – Cristian Rojas Oct 08 '15 at 03:03
  • 5
    Also `success` and `error` also removed in v1.6.0, can't be used anymore. – Burak Tokak Dec 12 '16 at 11:19
  • 2
    Note also that the documentation says "deprecated" but success() and error() are actually completely "removed"; don't be fooled. – tekHedd Dec 13 '16 at 19:11
4

If you want to handle server errors globally, you may want to register an interceptor service for $httpProvider:

$httpProvider.interceptors.push(function ($q) {
    return {
        'responseError': function (rejection) {
            // do something on error
            if (canRecover(rejection)) {
                return responseOrNewPromise
            }
            return $q.reject(rejection);
        }
    };
});

Docs: http://docs.angularjs.org/api/ng.$http

jarmod
  • 71,565
  • 16
  • 115
  • 122
Konstantin Tarkus
  • 37,618
  • 14
  • 135
  • 121
  • I think you have made a mistake there. To handle response errors you need to create a response interceptor not a request interceptor as you have done. – djd Aug 07 '13 at 19:12
  • The interceptor for angular is both request and response as of 1.1.x. – mlaccetti Oct 15 '13 at 03:45
3

Try this

function sendRequest(method, url, payload, done){

        var datatype = (method === "JSONP")? "jsonp" : "json";
        $http({
                method: method,
                url: url,
                dataType: datatype,
                data: payload || {},
                cache: true,
                timeout: 1000 * 60 * 10
        }).then(
            function(res){
                done(null, res.data); // server response
            },
            function(res){
                responseHandler(res, done);
            }
        );

    }
    function responseHandler(res, done){
        switch(res.status){
            default: done(res.status + ": " + res.statusText);
        }
    }
Naren Chejara
  • 1,124
  • 10
  • 7
1

I could not really work with the above. So this might help someone.

$http.get(url)
  .then(
    function(response) {
        console.log('get',response)
    }
  ).catch(
    function(response) {
    console.log('return code: ' + response.status);
    }
  )

See also the $http response parameter.

serv-inc
  • 35,772
  • 9
  • 166
  • 188