Troy
Troy

Reputation: 21872

How do I get the actual error from an AngularJS $http request?

I'm fairly new to AngularJS. I'm trying to get information on the actual error that occurred during a GET request. I've got the request set up like this:

$http.get(myUrl).then(mySuccessFunction).catch(function(reason) {
    //
});

The reason object that is passed to the catch has 5 properties:

  1. config - contains information on the request I sent (the URL, method, etc.)
  2. headers
  3. data - always seems to be null, regardless of the error that occurred
  4. status - always seems to be 0, regardless of the error that occurred
  5. statusText - always seems to be "", regardless of the error that occurred

I've also looked at using the $http.get(url).success().error() technique, but the error() function is passed generally the same (seemingly useless) information, only in parameter form, rather than as properties of a single object.

From the browser console, I can see that the request is triggering a status 500, or ERR_CONNECTION_REFUSED, etc. However, I'm not seeing how to get that information from the reason object...

How do I get information on the actual error that occurred during the request?


UPDATE:
I found that the issue, for me, was actually a CORS issue. See my answer below.

Upvotes: 3

Views: 2539

Answers (3)

OzBob
OzBob

Reputation: 4520

here's the work around to get StatusText (as pointed out that some mobile browsers strip out DATA from successfull responses: https://stackoverflow.com/a/28470163/1586498

I have also discovered that .success and .error on $http in Angular does not pass the StatusText, you have to use .then(response)

Upvotes: 0

Troy
Troy

Reputation: 21872

I found that, in my case, the problem was a CORS issue, which was hiding the real issue.

Before posting the question, I was testing 2 error cases:

  1. Server Unavailable (ERR_CONNECTION_REFUSED)
  2. Server encountered an internal error (status 500)

Both error conditions were giving me exactly the same "error" data (null/0/"" for data/status/statusText) via the angular catch/error function. For (1) null/0/"" is the correct response. For (2), when my dev server was (intentionally) triggering status 500 response, it wasn't handling CORS correctly for that error response.

Apparently, for CORS issues, null/0/"" is also the correct "error" data for an Angular-generated GET.

After posting this question, I tried other error conditions (404, etc.), and started getting more useful data passed to the catch/error function.

Upvotes: 1

Bioto
Bioto

Reputation: 1117

$http.get('/someUrl').success(function(data, status, headers, config) {

}).
error(function(data, status, headers, config) {

});

the status variable should provide the error code and headers should provide better details on the request

Upvotes: 0

Related Questions