简体   繁体   中英

AngularJS $http service never calls the error handler

I have this code:

$http
.post('/api/login', $scope.user)
.success(function (data, status, headers, config) {
  // code
})
.error(function (data, status, headers, config) {
  // code
});

It works, but even though the server returns an exception (status 500) or a bad request (400) or an unauthorized request (401) it still calls the success handler.

This is an example response from the server (my server is ASP.NET Web API 2):

HTTP/1.1 400 Bad Request
Cache-Control: no-cache
Pragma: no-cache
Expires: -1
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?QzpcRG9jdW1lbnRzXFRpbWVUYWJsZVxqYW4tMjAxNFwxMVxUaW1lVGFibGVcVGltZVRhYmxlXGFwaVxsb2dpbg==?=
X-Powered-By: ASP.NET
Date: Sun, 23 Feb 2014 10:56:09 GMT
Content-Length: 0

You need to make sure you are returning a rejected promise in your interceptor for the 'responseError' property. if you are simply returning the response or not implementing the 'responseError' then the success function will always run regardless of the status code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM