【问题标题】:Duck Typing with JSON object - try/except?使用 JSON 对象进行 Duck 键入 - 尝试/排除?
【发布时间】:2014-10-25 03:33:26
【问题描述】:

在 AngularJS 中,我有一个 api 请求发出并返回一个 JSON。 JSON 存储为对象data,我使用data.Automation.Status 来检查Status 中的字符串。

有一些 JSON 错误可能会上升(在 http 200 成功并成功返回 json 之后):

  1. 整个 JSON 可以返回一个空白字符串“”
  2. 数据 JSON 对象可能存在,但自动化 JSON 对象可能未定义
  3. 对象Automation 的属性Status 可能未定义或为空字符串

来自 python,所有这些可能的情况都可以在 try/except 块中轻松处理。

Try: 
  do something with JSON 
except (blah, blah)
  don't error out because JSON object is broken, but do this instead

我看到 Angular 有 $errorHandler 服务,可以使用自定义处理程序进行修改。但我不确定这是否可以以与我正在寻找的鸭子类型相同的方式使用。

如何在 AngularJS 中进行鸭式打字?具体来说,对于上面列表中提到的 JSON 对象错误场景?

我现在如何使用data.Automation.Status

 if (iteration < Configuration.CHECK_ITERATIONS && data.Automation.Status !== "FAILED") {
    iteration++;
    return $timeout((function() {
      return newStatusEvent(eventId, url, deferred, iteration);
    }), Configuration.TIME_ITERATION);
  } else {
    err = data.Automation.StatusDescription;
    return deferred.reject(err);
  }

【问题讨论】:

  • 与问题无关,但我发现这里使用 $timeout 真的很奇怪:你不应该使用 deferred.resolve() 代替吗?
  • 你知道你可以在 JavaScript 中做同样的事情,不是吗?

标签: javascript angularjs error-handling duck-typing


【解决方案1】:

以下是我为同一问题找到解决方案的方法。
它保持最小化,所有测试都集中在一个块中。

$http.get('/endpoint1').success(function(res) {
    try {
        // test response before proceeding
        if (JSON.stringify(res).length === 0) throw 'Empty JSON Response!';
        if (!res.hasOwnProperty('Automation')) throw 'Automation object is undefined!';
        if (!res.Automation.hasOwnProperty('Status') || res.Automation.Status !== 'SUCCESS')
            throw 'Automation Status Failed!';
    } catch (err) {
        // handle your error here
        console.error('Error in response from endpoint1: ' + err);
    }

    // if your assertions are correct you can continue your program
});

【讨论】:

    【解决方案2】:

    想到处理这种情况的最佳方法是使用 $parse,因为它可以很好地处理 undefined。你可以这样做:

    $http.get('/endpoint1').success(function(res) {
        try {
            // test response before proceeding
            if (angular.isUndefined($parse('Automation.Status')(res))) {
              throw 'Automation Status Failed!';
            }
        } catch (err) {
            // handle your error here
            console.error('Error in response from endpoint1: ' + err);
        }
    
        // if your assertions are correct you can continue your program
    });
    

    您可以在 plunker 中看到 $parse 如何处理您的场景。

    【讨论】:

    • 我喜欢这个,因为它看起来最干净。无论如何我可以给你额外的赏金吗?
    • 不确定,不过我很高兴我的回答很有用! :D
    【解决方案3】:

    取决于您想要获得的复杂程度。如果你想使用 coffeescript,有一个不错的 ?运算符:json.knownToExist.maybeExists?.maybeAlsoExists?() 永远不会出错,并且只会在它存在时调用 MaybeAlsoExists。

    否则,您可以使用 typeof 检查:

    foo = {a: 1, b: 2}
    typeof foo === 'object'
    typeof foo.bar === 'undefined'
    

    我的印象是 javascript 中的 try/catch 块相对昂贵。因此,您可能想要手动测试 json,特别是如果您的服务的不同返回值是您所谓的“正常”响应。例外,IMO,应该用于exception的发生,而不是健全性检查。

    【讨论】:

      猜你喜欢
      • 2011-02-28
      • 1970-01-01
      • 2021-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多