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

catch() on angularjs $http.get() call doesn't suppress error

我有以下代码(为了示例而简化和 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 的 $httpan equivalent example here,它的行为符合我的预期:

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 情况下处理的错误?

您可以在链接的 angularjs 模块的第 8416 行找到解释。他们只是在 catch 语句中 console.error 。您可以覆盖此行为,f.e。通过空处理程序:

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

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

....

AngularJS 1.6 的发布修复了该行为:

来自 GitHub 提交:

fix($q): treat thrown errors as regular rejections

Previously, errors thrown in a promise's onFulfilled or onRejected handlers were treated in a slightly different manner than regular rejections: They were passed to the $exceptionHandler() (in addition to being converted to rejections).

AngularJS GitHub Commit e12eea

另见 AngularJS Developer Guide - Migrating to V1.6 - $q