Javascript 在 angular $http 服务中,如何捕捉错误的“状态”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27507678/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:14:21  来源:igfitidea点击:

In angular $http service, How can I catch the "status" of error?

javascriptangularjs

提问by nujabes

I'm reading a book called, "Pro Angular JS". However, I have a question about how to catch a status of error.

我正在阅读一本名为“Pro Angular JS”的书。但是,我有一个关于如何捕获错误状态的问题。

What I coded is :

我编码的是:

$http.get(dataUrl)
    .success(function (data){
        $scope.data.products = data;
    })
    .error(function (error){
        $scope.data.error=error;
        console.log($scope.data.error.status); // Undefined!
        // (This is the spot that I don't get it.)                                         
    });

If I code "console.log($scope.data.error.status);" , why does the argument of console.log is undefined?

如果我编码“console.log($scope.data.error.status);” ,为什么console.log的参数是undefined?

In the book, there are sentence, "The object passed to the error function defines status and message properties."

书中有一句话“传递给错误函数的对象定义了状态和消息属性”。

So I did $scope.data.error.status

所以我做了 $scope.data.error.status

Why is it wrong?

为什么会出错?

回答by visar_uruqi

The $httplegacy promise methods successand errorhave been deprecated. Use the standard thenmethod instead. Have a look at the docs https://docs.angularjs.org/api/ng/service/$http

$http传统方法的承诺success,并error已被弃用。请改用标准then方法。看看文档https://docs.angularjs.org/api/ng/service/$http

Now the right way to use is:

现在正确的使用方法是:

// Simple GET request example:
$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.
});

The response object has these properties:

响应对象具有以下属性:

  • data – {string|Object} – The response body transformed with the transform functions.
  • status – {number} – HTTP status code of the response.
  • headers – {function([headerName])} – Header getter function.
  • config – {Object} – The configuration object that was used to generate the request.
  • statusText – {string} – HTTP status text of the response.
  • data – {string|Object} – 使用转换函数转换的响应主体。
  • status – {number} – 响应的 HTTP 状态代码。
  • 标头 – {function([headerName])} – 标头 getter 函数。
  • config – {Object} – 用于生成请求的配置对象。
  • statusText – {string} – 响应的 HTTP 状态文本。

A response status code between 200 and 299 is considered a success status and will result in the success callback being called.

200 到 299 之间的响应状态代码被认为是成功状态,并将导致成功回调被调用。

回答by DoctorMick

Your arguments are incorrect, error doesn't return an object containing status and message, it passed them as separate parameters in the order described below.

您的参数不正确,错误不会返回包含状态和消息的对象,而是按照下面描述的顺序将它们作为单独的参数传递。

Taken from the angular docs:

取自angular 文档

  • data – {string|Object} – The response body transformed with the transform functions.
  • status – {number} – HTTP status code of the response.
  • headers – {function([headerName])} – Header getter function.
  • config – {Object} – The configuration object that was used to generate the request.
  • statusText – {string} – HTTP status text of the response.
  • data – {string|Object} – 使用转换函数转换的响应主体。
  • status – {number} – 响应的 HTTP 状态代码。
  • 标头 – {function([headerName])} – 标头 getter 函数。
  • config – {Object} – 用于生成请求的配置对象。
  • statusText – {string} – 响应的 HTTP 状态文本。

So you'd need to change your code to:

因此,您需要将代码更改为:

$http.get(dataUrl)
    .success(function (data){
        $scope.data.products = data;
    })
    .error(function (error, status){
        $scope.data.error = { message: error, status: status};
        console.log($scope.data.error.status); 
  }); 

Obviously, you don't have to create an object representing the error, you could just create separate scope properties but the same principle applies.

显然,您不必创建表示错误的对象,您可以只创建单独的范围属性,但适用相同的原则。

回答by Nitsan Baleli

UPDATED: As of angularjs 1.5, promise methods success and error have been deprecated. (see this answer)

更新:从 angularjs 1.5 开始,promise 方法成功和错误已被弃用。(见这个答案

from current docs:

当前文档

$http.get('/someUrl', config).then(successCallback, errorCallback);
$http.post('/someUrl', data, config).then(successCallback, errorCallback);


you can use the function's other arguments like so:

您可以像这样使用函数的其他参数:

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

see $httpdocs:

请参阅$http文档:

// Simple GET request example :
$http.get('/someUrl').
  success(function(data, status, headers, config) {
    // this callback will be called asynchronously
    // when the response is available
  }).
  error(function(data, status, headers, config) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });

回答by drzaus

Since $http.getreturns a 'promise' with the extra convenience methods successand error(which just wrap the result of then) you should be able to use (regardless of your Angular version):

由于$http.get使用额外的便利方法返回“承诺”success并且error(仅包装 的结果then)您应该能够使用(无论您的 Angular 版本如何):

$http.get('/someUrl')
    .then(function success(response) {
        console.log('succeeded', response); // supposed to have: data, status, headers, config, statusText
    }, function error(response) {
        console.log('failed', response); // supposed to have: data, status, headers, config, statusText
    })


Not strictly an answer to the question, but if you're getting bitten by the "my version of Angular is different than the docs" issue you can always dump all of the arguments, even if you don't know the appropriate method signature:

严格来说不是这个问题的答案,但如果你被“我的 Angular 版本与文档不同”问题所困扰,你总是可以转储所有的arguments,即使你不知道适当的方法签名:

$http.get('/someUrl')
  .success(function(data, foo, bar) {
    console.log(arguments); // includes data, status, etc including unlisted ones if present
  })
  .error(function(baz, foo, bar, idontknow) {
    console.log(arguments); // includes data, status, etc including unlisted ones if present
  });

Then, based on whatever you find, you can 'fix' the function arguments to match.

然后,根据您找到的任何内容,您可以“修复”要匹配的函数参数。

回答by Timofey

From the official angular documentation

来自官方角度文档

// Simple GET request example :
$http.get('/someUrl').
  success(function(data, status, headers, config) {
    // this callback will be called asynchronously
    // when the response is available
  }).
  error(function(data, status, headers, config) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });

As you can see first parameter for error callback is data an status is second.

如您所见,错误回调的第一个参数是数据,状态是第二个。

回答by Rasalom

Response status comes as second parameter in callback, (from docs):

响应状态作为回调中的第二个参数,(来自 docs):

// Simple GET request example :
$http.get('/someUrl').
  success(function(data, status, headers, config) {
    // this callback will be called asynchronously
    // when the response is available
  }).
  error(function(data, status, headers, config) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });