$http error handling in AngularJS
Asked Answered
C

3

5

$http in my AngularJS project not able to recognize 40X(401,403,405...) errors on iOS. I am using 1.2.10 AngularJS version and Cordova version 3.4.0.

Below is the code I am using:

TE_SERVICES.factory('hello',function ($http,$rootScope) {
return {
loginUser: function(userCredentials,successCallback,errorCallback){
          $http({
               method: "GET",
               url: "data/example.json",
               headers: {"Authorization":'Basic '+userCredentials},
             }).then(function(response){
                                successCallback(response.data);
                                console.log("Success------"+JSON.stringify(response))
             },function(data, status, headers, config){
                                errorCallback(data);
                                console.log("Error------"+JSON.stringify(data)+" "+status)
             })

        }
    }
 });

hello.loginUser($rootScope.encodedUserCredencials,function(persons) {
                // success handler
            }, function(data) {
                // error handler
                console.log(data.status+"===="+status)
                });

data.status is returning 0 and status returns undefined. Please help me to resolve this issue.

Tried to include the domain in whitelist on IOS.But no solution :( It still gives the same response.

But the same code works absolutely fine in Android. Please help me to resolve this issue.

Thanks in advance :)

Compunction answered 6/5, 2014 at 5:53 Comment(1)
I have the same problem. Did you found a solution?Prosperity
K
7

So you r using the $http from angular. Do you use the error callback or the second function in the then callback ?

Example

$http.get("someUrl")
  .success(function(response){}) // if http code == 200
  .error(function(response){}) // else

Or with then, that can take 2 functions. The first is the onSuccess, the second the onError function.

$http.get("someUrl")
  .then(function(response){
            // if http code == 200
   },
    function(response){
            // else
   }); 

The response parameter does also contain the error codes.

Consider using a $httpInterceptor to handle all errorcodes at the same place, instead handling them in every http callback.

UPDATE: It seems, that the angular doc is incomplete/wrong for the success callback. It doesnt pass 4 parameter there. It does pass a response object that contains all the information about request+response and the passed data.

Update to the edit:

Dont write callbacks by yourself. Use angular promises:

TE_SERVICES.factory('hello',function ($http,$rootScope) {
   return {
       loginUser: function(userCredentials){
          return $http({
             method: "GET",
             url: "data/example.json",
             headers: {"Authorization":'Basic '+userCredentials},
          }).then(function(response){
             return response.data;                                    
          },function(response){
             return response;                                
          });    
        }
    }
 });

hello.loginUser($rootScope.encodedUserCredencials)
     .then(function(persons) {                // success handler

     }, function(data) { // error handler
       console.log(data);
     });

Try this and tell me if the console.log logs something.

Kraigkrait answered 6/5, 2014 at 6:8 Comment(3)
I am using with then , Have edited the question .please have a look .Compunction
I works fine in android, problem is in IOS, when i give invalid credentials in android it throws 401 error, but in IOS it shows data.status as 0.:(Compunction
according to docs.angularjs.org/api/ng/service/$http "The $http legacy promise methods success and error have been deprecated. Use the standard then method instead."Wiskind
P
3

I had exactly the same problem. Cordova app, angular js, IPhone and 401 requests are not received in angular js http interceptor. They work fine on android devices.

My finding was that IPhone browser is handling those at a higher lever and trying to use WWW-Authenticate information to do authentication. This is why the response does not get to angular.

The only solution I found, was to change my service to return 400 instead of 401 in case of an api request. In this case I return 400 with an error message that I handle on client side.

I hope this helps.

Prosperity answered 8/2, 2016 at 7:25 Comment(0)
A
1

My issue with the 403 status code was that my backend returned a response with status 403 but the body of a response did not contain a JSON string. It contained just a string - Authentication Failed.

The rejection variable was an object Error. I encoded the body and the rejection variable contains a valid response error object. To handle HTTP errors I use interceptors.

$httpProvider.interceptors.push(function($q, $location, redirect, HTTP_CODES) {
            return {
                'responseError': function(rejection) {
                    if (rejection.status === HTTP_CODES.FORBIDDEN) {
                        redirect('/login', $location.url());
                    }

                    return $q.reject(rejection);
                }
            };
        });
Anselmi answered 14/5, 2020 at 20:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.