【问题标题】:Promises - catch is not working承诺 - 捕捉不起作用
【发布时间】:2018-07-21 00:15:50
【问题描述】:

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

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

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

【问题讨论】:

  • 认为您将 try/catch 与您承诺的 catch 处理程序混淆了。第一个是抛出一个合适的,因为 null 不是可接受的输入参数。您需要将整个内容包装在 try {...} catch (err) {...}
  • $http.get 方法在创建并返回一个承诺之前 抛出错误。

标签: javascript angularjs promise


【解决方案1】:

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

专门用于处理承诺解决过程中发生的异常情况。

在这种情况下,异常(抛出一个 fit)发生在 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";
}

【讨论】:

  • @BShaps 感谢 :) 初稿匆匆而过,审查时肯定需要一些代码来清楚地说明。
【解决方案2】:

您需要了解此 catch 正在等待您的 get 呼叫“拒绝”。

换句话说,你的$http.get 正在触发一个错误并且永远不会返回一个承诺......这样,你就不能直接从错误中执行一个catch,明白了吗?

如果你有$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 :)

如果您的 url 来自不同的来源(这就是为什么您有时会获得 null 值),您可能应该在尝试获取它之前对其进行验证,如下所示:

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

【讨论】:

    【解决方案3】:

    这将抛出错误:$http:badreq 错误请求配置。它在请求参数级别存在问题,其中字符串/url 是预期的,但不是空的。因此不要进入街区。这就是它没有触发 catch 的原因。

    Angular 会抛出的错误如下 -

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-05
      • 1970-01-01
      • 2011-02-12
      • 1970-01-01
      • 1970-01-01
      • 2017-08-07
      • 2017-04-29
      • 2020-06-23
      相关资源
      最近更新 更多