鸭子用JSON对象打字 - 尝试/除外?

时间:2014-08-31 22:13:13

标签: javascript angularjs error-handling duck-typing

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

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

  1. 整个JSON可以返回一个空白字符串“”
  2. 数据JSON对象可能存在,但Automation JSON对象可能未定义
  3. 对象Status的属性Automation可能未定义或为空字符串
  4. 来自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对象错误scenerios?

    目前我如何使用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);
      }
    

3 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分: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如何处理您的方案。

答案 2 :(得分:1)

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

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

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

我认为javascript中的try / catch块相对较贵。因此,您可能希望手动测试json,特别是如果您的服务的不同返回值是您要调用的正常情况。响应。例外,IMO应该用于例外事件,而不是健全性检查。