Poiro
Poiro

Reputation: 1011

$http request success with error

I have the following simple code:

$http(request)
    .success(function(data){                                            
                ...
            })
    .error(function(data){
                ...
            });

One issue I get is when the response has caused an error, I get back an error in the JSON response, which I can see via data.error, however the way I have it working at the moment data.error is actually successful, rather than an error.

What would be the best way to handle this? Would it simple as an:

if (data.error){ ....

Upvotes: 1

Views: 2033

Answers (2)

Ian Oxley
Ian Oxley

Reputation: 11056

According to the Angular docs:

A response status code between 200 and 299 is considered a success status and will result in the success callback being called. Note that if the response is a redirect, XMLHttpRequest will transparently follow it, meaning that the error callback will not be called for such responses.

So if you're returning data.error in your JSON, but the response is being returned with a HTTP status code of 200, your .error handler will not get called.

To answer your question then, yes - doing something like if (data.error) {... } should do the trick.

Upvotes: 2

Sebastian Pederiva
Sebastian Pederiva

Reputation: 381

first at all you should not use .success and .error (see https://docs.angularjs.org/api/ng/service/$http#deprecation-notice)

so you should use in the following way:

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

hope this will help you!

Upvotes: 1

Related Questions