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.

6 Answers 6

148

You need to add an additional parameter:

$http.get(url).then(
    function(response) {
        console.log('get',response)
    },
    function(data) {
        // Handle error here
    })
Sign up to request clarification or add additional context in comments.

3 Comments

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.)
Also note: data.config.url contains the full url + params , in case you passed params next to url
I don't know but it is not working for my case. Always the response code is executed.
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.

4 Comments

I'd totally go for this solution.
it must be accepted answer, because .error() method does not work with 500 errors! Please accept.
Best solution after success & remove is removed in v1.6.0
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 fails
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.

5 Comments

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: To be more accurate, .then() returns a new promise. .success() and .error() do not, they both return the original promise provided by get(url).
It's important also to keep in mind that success and error callbacks for $http api will be deprecated.
Also success and error also removed in v1.6.0, can't be used anymore.
Note also that the documentation says "deprecated" but success() and error() are actually completely "removed"; don't be fooled.
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

2 Comments

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.
The interceptor for angular is both request and response as of 1.1.x.
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);
        }
    }

Comments

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.

Comments

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.