Duck用JSON对象打字-try/except

Duck Typing with JSON object - try/except?

本文关键字:-try except JSON 对象 Duck      更新时间:2023-09-26

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

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

  1. 整个JSON可以返回一个空白字符串"
  2. 数据JSON对象可能存在,但Automation 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);
  }

以下是我如何找到相同问题的解决方案
它使它保持最小,并且所有测试都分组在一个块中。

$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
});

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

$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如何处理您的场景。

取决于您想要获得的复杂程度。如果你想用咖啡脚本,有一个不错的?operator:json.knownToExist.maybeExists?.maybeAlsoExists?()永远不会出错,并且只会在存在的情况下调用maybeAlsoExists。

否则,您可以使用支票类型:

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

我的印象是javascript中的try/catch块相对昂贵。因此,您可能需要手动测试json,特别是如果服务的不同返回值是您所称的"正常"响应。例外情况IMO应用于异常事件,而不是健全性检查。