为什么下面的代码没有捕获到抛出的异常?
$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/