javascript - promise - catch 不工作

标签 javascript angularjs promise

为什么下面的代码没有捕获到抛出的异常?

$http.get(null)        // <- this throws a fit
.catch(function (e) {
  console.log(e);      // <- this is not being triggered
});

Error: [$http:badreq] Http request configuration url must be a string or a $sce trusted object. Received: null https://errors.angularjs.org/1.7.2/$http/badreq?p0=null

最佳答案

.catch() 不能替代普通的 try catch

专门用于处理promise解析过程中出现的异常情况。

在这种情况下,异常(抛出异常)发生在 promise 解决过程之外。

您向 $http.get 方法提供无效输入导致在创建 XHR 之前引发异常,不是HTTP 请求或任何后续处理出现问题.

这相当于正在发生的事情:

try {
  $http.get(throwAnException()) 
    // .catch isn't even being evaluated!
    .catch(function(e) { 
      console.error(e); // no chance of being called      
    });

} catch (e) {
  // I would be evaluated
  console.error(e);
}

function throwAnException() {
  throw "An error before we even start";
}

关于javascript - promise - catch 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51451751/

相关文章:

javascript - Backbone View 无法访问 jQuery 选择器

javascript - angularJs 从数组中排除已经选择的项目

javascript - Node.js/Javascript 多重递归 promise 在 View 中返回

javascript - 中止错误 : The play() request was interrupted by a call to pause()

javascript - 带有 src 和内容的 script-Tag 是什么意思?

JavaScript - 未捕获的 ReferenceError : checkAnswer is not defined, 函数不在范围内?

javascript - [Vue warn] : Invalid prop: type check failed for prop "eventKey". 预期字符串、数字、获取数组并避免使用非原始值作为键

angularjs - 如何从 angular.js 数组中删除元素/节点

javascript - Angular : ng-repeat does not update on view after removing the element

javascript - 处理异步函数的同步方式,两层深度