在 AngularJS 中,我发出一个 api 请求并返回一个 JSON。 JSON 存储为对象 data
,我使用 data.Automation.Status
检查 Status
中的字符串。
有一些 JSON 错误可能会增加(在 json 成功返回的 http 200 成功之后):
- 整个 JSON 可以返回一个空字符串 ""
- 数据 JSON 对象可以存在,但自动化 JSON 对象可以未定义
- 对象
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/