简体   繁体   English

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

[英]In angular $http service, How can I catch the “status” of error?

I'm reading a book called, "Pro Angular JS". 我正在读一本名为“Pro Angular JS”的书。 However, I have a question about how to catch a status of error. 但是,我有一个关于如何捕获错误状态的问题。

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);" 如果我编码“console.log($ scope.data.error.status);” , why does the argument of console.log is undefined? ,为什么console.log的参数未定义?

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? 为什么这是错的?

The $http legacy promise methods success and error have been deprecated. $http遗留承诺方法successerror已被弃用。 Use the standard then method instead. 使用标准then方法来代替。 Have a look at the docs https://docs.angularjs.org/api/ng/service/ $http 看看文档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. data - {string | Object} - 使用转换函数转换的响应体。
  • status – {number} – HTTP status code of the response. status - {number} - 响应的HTTP状态代码。
  • headers – {function([headerName])} – Header getter function. headers - {function([headerName])} - 头部getter函数。
  • config – {Object} – The configuration object that was used to generate the request. config - {Object} - 用于生成请求的配置对象。
  • statusText – {string} – HTTP status text of the response. 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之间的响应状态代码被视为成功状态,将导致调用成功回调。

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 : 取自角度文档

  • data – {string|Object} – The response body transformed with the transform functions. data - {string | Object} - 使用转换函数转换的响应体。
  • status – {number} – HTTP status code of the response. status - {number} - 响应的HTTP状态代码。
  • headers – {function([headerName])} – Header getter function. headers - {function([headerName])} - 头部getter函数。
  • config – {Object} – The configuration object that was used to generate the request. config - {Object} - 用于生成请求的配置对象。
  • statusText – {string} – HTTP status text of the response. 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. 显然,您不必创建表示错误的对象,您可以创建单独的范围属性,但同样的原则适用。

UPDATED: As of angularjs 1.5, promise methods success and error have been deprecated. 更新:从angularjs 1.5开始,promise方法成功和错误已被弃用。 (see this answer ) (见这个答案

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 $http docs: 请参阅$ http 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.
  });

Since $http.get returns a 'promise' with the extra convenience methods success and error (which just wrap the result of then ) you should be able to use (regardless of your Angular version): 由于$http.get返回一个带有额外的便利方法“承诺” successerror (这只是包装的结果, then ),你应该能够使用(无论你的角度版本):

$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 ,即使您不知道相应的方法签名,也可以转储所有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. 然后,根据您找到的任何内容,您可以“修复”要匹配的函数参数。

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. 正如您所看到的,错误回调的第一个参数是数据,状态是第二个。

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.
  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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