承诺-捕获无效

时间:2018-07-21 00:15:50

标签: javascript angularjs promise

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

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

错误:[$ http:badreq] Http请求配置url必须是字符串或$ sce受信任对象。收到:null   https://errors.angularjs.org/1.7.2/$http/badreq?p0=null

3 个答案:

答案 0 :(得分:4)

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

它专门用于处理在承诺解决过程中发生的特殊情况。

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

您为$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";
}

答案 1 :(得分:4)

您需要了解,此catch正在等待您的get通话的“拒绝”。

换句话说,您的$http.get触发了一个错误,并且从不返回承诺...这样,您不能直接从错误中执行捕获,得到它吗?

如果您有$http.get("xyz"),它将执行其操作并拒绝,因此被您的渔获物捕获。

您正在做的事情由此产生

// step 1
$http.get(null)
    .catch()

// step 2
ERROR
    .catch() // will not even get here, but if it did, it wouldn't work either

同时,如果您的get可以工作,但被拒绝了,那么您将:

// step 1
$http.get('someFailingURL')
    .catch()

// step 2
RejectedPromise
    .catch() // gonna work :)

如果您的网址来自其他来源(这就是为什么有时会获得一个null值的原因),则您应该在尝试获取它之前先对其进行验证,例如:

if (yourVariableURL !== null) {
    $http.get(yourVariableURL)
        .catch()
} else {
    console.log('Invalid url');
}

答案 2 :(得分:0)

这将引发错误:$ http:badreq错误的请求配置。它在请求参数级别存在问题,该参数期望字符串/ URL,但不能为空。因此不要进入块内。这就是它不触发捕获的原因。

Angular将抛出以下错误-

  

Http请求配置url必须是字符串或$ sce受信任对象。收到:空

当传递给$ http服务的请求配置参数不是有效的对象时,会发生此错误。 $ http需要一个参数,即请求配置对象,但接收到的参数不是对象或不包含有效属性。

要解决此错误,请确保将有效的请求配置对象传递给$ http。

此外,如果需要捕获此代码块本身的问题,请将其包装在try-catch块中。