Error handling in AngularJS http get then construct
Asked Answered
B

6

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.

Briarroot answered 13/6, 2013 at 5:58 Comment(0)
T
148

You need to add an additional parameter:

$http.get(url).then(
    function(response) {
        console.log('get',response)
    },
    function(data) {
        // Handle error here
    })
Triturate answered 13/6, 2013 at 6:3 Comment(3)
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.)Coppery
Also note: data.config.url contains the full url + params , in case you passed params next to urlAmbrosine
I don't know but it is not working for my case. Always the response code is executed.Hocker
S
59

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.

Suspire answered 17/2, 2016 at 13:45 Comment(4)
I'd totally go for this solution.Insurgent
it must be accepted answer, because .error() method does not work with 500 errors! Please accept.Elkin
Best solution after success & remove is removed in v1.6.0Theressa
NOTE that .catch also executes if .then has internal error (like calling non-existing method) while .then(success, error) will handle error only if request itself failsIne
K
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.

Kirven answered 13/6, 2013 at 6:4 Comment(5)
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.Brande
@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).Felicefelicia
It's important also to keep in mind that success and error callbacks for $http api will be deprecated.Jot
Also success and error also removed in v1.6.0, can't be used anymore.Theressa
Note also that the documentation says "deprecated" but success() and error() are actually completely "removed"; don't be fooled.Mellon
C
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

Contortionist answered 13/6, 2013 at 6:20 Comment(2)
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.Alboran
The interceptor for angular is both request and response as of 1.1.x.Foresight
L
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);
        }
    }
Lohse answered 7/3, 2016 at 9:17 Comment(0)
I
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.

Itis answered 13/6, 2019 at 15:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.