2014-08-31 49 views
1

在AngularJS中,我有一個api請求出去並返回一個JSON。 JSON存儲爲對象data,我使用data.Automation.Status檢查Status中的字符串。鴨與JSON對象鍵入 - 嘗試/除?

有可能上升(與JSON HTTP 200成功後成功返回)幾個JSON錯誤:

  1. 整個JSON可能會返回一個空字符串「」
  2. 數據JSON對象可以存在,但自動化JSON對象可能是不確定的
  3. 物業Status對象Automation的可能是未定義或空字符串

今兒g來自python,所有這些可能的情況都可以在try/except塊中輕鬆處理。

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

我看到角有$ 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); 
    } 
+1

沒有真正與問題有關,但我發現使用$ timeout在這裏真的很奇怪:你不應該使用deferred.resolve()代替嗎? – 2014-09-09 18:48:38

+0

你知道你可以在JavaScript中完全相同,不是嗎? – zeroflagL 2014-09-10 21:12:37

回答

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 $解析如何處理您的場景。

+0

我喜歡這個,因爲它看起來最乾淨。無論如何,我可以給你額外的賞金點數嗎? – dman 2014-09-12 22:10:59

+1

不知道,我很高興我的答案雖然有用! :d – Wawy 2014-09-12 23:24:43

1

根據你想多麼複雜獲得。如果你想使用咖啡標記,有一個很好的?運營商:json.knownToExist.maybeExists?.maybeAlsoExists?()將永遠不會錯誤,並且只會調用maybeAlsoExists(如果存在)。

否則,你可以使用的typeof檢查:

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

我認爲try/catch塊在JavaScript中是比較昂貴的印象是。所以你可能想要手動測試json,特別是如果你的服務的不同返回值是你所說的'正常'響應。例外,國際海事組織,應該用於例外發生,而不是健全性檢查。

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