javascript - 鸭子类型(duck typing)用 JSON 对象打字 - 尝试/除外?

标签 javascript angularjs error-handling duck-typing

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

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

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

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

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

我看到 angular 有 $errorHandler 服务,可以用自定义处理程序修改。但我不确定这是否可以按照我正在寻找的鸭子类型(duck typing)方式使用。

我怎样才能在 AngularJS 中进行 duck typing?具体是针对上面列举的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);
  }

最佳答案

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

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

关于javascript - 鸭子类型(duck typing)用 JSON 对象打字 - 尝试/除外?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25596784/

相关文章:

javascript - php 文件中未定义 javascript 函数时出现错误

json - AngularJS JSON 格式以逗号分隔

c# - 如何在回调 channel 上抛出错误通知客户端?

angularjs - Protractor:获取与xpath绑定(bind)的值

javascript - 使用 Angular.js - 如何从需要身份验证的后端提供二进制数据?

python - TypeError : 'str' object is not callable with input()

javascript - 管道中的 csv 解析错误处理

javascript - 从 console.log 自定义打印?

javascript - 使用视口(viewport)宽度 (vw) 在 ReactJs 中进行预览,以按小比例放置元素

javascript - 为什么 Object.assign 没有替换我的新对象中的键?