在angularjs $ http.get()调用上catch()不会抑制错误

时间:2019-02-26 00:46:47

标签: javascript angularjs error-handling angular-promise

我有以下代码(为示例起见,简化为running in codepen):

var app = angular.module("httptest", []);

app.controller("getjson", ["$scope", "$http", function($scope, $http) {
  $http.get("https://codepen.io/anon/pen/LVEwdw.js").
  then((response) => {
    console.log(response.data)
    console.log('in then')
    throw 'the error'
  }).catch((e) => {
    console.log('in the catch')
    console.log(e);
  });
}]);

我在这里的期望是,如果输入了catch()块,则该错误将不会在控制台中显示,除非显式记录的位置(即,它不会以红色显示)。但是,情况并非如此,红色错误消息会打印到控制台,然后输入catch()块。我尝试设置不使用AngularJS的$http的{​​{3}},并且其行为符合我的期望:

var promise1 = new Promise(function(resolve, reject) {
  resolve();
});

promise1.then((result) => {
  console.log('about to throw error')
  throw 'hey'
 }).catch(function(error) {
  console.log(error);
});

在此示例中,没有红色错误使其通过。

这是怎么回事,有可能在$http情况下抑制已处理的错误吗?

2 个答案:

答案 0 :(得分:1)

您可以在链接的angularjs模块中的第8416行找到说明。它们只是catch语句中的console.error。您可以覆盖此行为,例如通过空处理程序:

angular.module('exceptionOverride', []).factory('$exceptionHandler', () => (exception, cause) });

var app = angular.module("httptest", ['exceptionOverride']);

....

答案 1 :(得分:1)

该行为在AngularJS 1.6的发布中得到了解决:

从GitHub提交:

  

fix($ q):将抛出的错误视为常规拒绝

     

以前,在诺言的onFulfilledonRejected处理程序中引发的错误在   与常规拒绝方式略有不同:   它们被传递到$exceptionHandler()(除了转换为拒绝之外)。

     

AngularJS GitHub Commit e12eea

另请参阅AngularJS Developer Guide - Migrating to V1.6 - $q