在移動設備上,錯誤可能與模擬器上的錯誤大不相同,因爲我們正在處理表面下的本地API。見networking section in the developer guide的錯誤處理部分:
有兩種截然不同的放置在那裏你可以處理網絡故障:
- 的
ConnectionRequest
- 通過重寫回調方法
- 的
NetworkManager
錯誤處理程序
請注意,NetworkManager
錯誤處理程序優先,因此您可以通過消耗錯誤來定義網絡錯誤處理的全局策略。
E.g.如果我想阻止任何展示給用戶的所有網絡錯誤,我可以做這樣的事情:
NetworkManager.getInstance().addToQueue(request);
NetworkManager.getInstance().addErrorListener((e) -> e.consume());
錯誤監聽器與NetworkEvent匹配錯誤首先被調用。消費該事件可以防止它沿着鏈條進一步傳播到ConnectionRequest回調中。
我們還可以覆蓋請求中各種類型的錯誤回調,例如在發生服務器錯誤代碼的情況下我們可以這樣做:
ConnectionRequest request = new ConnectionRequest(url, false) {
protected void handleErrorResponseCode(int code, String message) {
if(code == 444) {
// do something
}
}
protected void handleException(Exception err) {
// handle exception that occurred. Notice you can either have this or have the listener on the NetworkManager
}
protected void readResponse(InputStream input) {
// just read from the response input stream
}
};
NetworkManager.getInstance().addToQueue(request);
如何處理ConnectionRequest類的超時異常? –
它將在錯誤偵聽器/ handleException方法中顯示它自己。 –
你能用例子來解釋嗎? –