2016-01-20 58 views
0

有沒有一種很好的方法來捕獲有關連接問題的Angular中的錯誤?

服務$ HTTP POST:

dossierService.getDossier(uid) 

    .then(function (result) { 

     vm.dossier = result.dossier; 

    }, function (error) { 

     handleError(error) 

    });//end dossierService.getDossier(uid) 

如果出現連接問題,它會返回一個錯誤:

POST http://192.168.25.1:8080/api/query net::ERR_CONNECTION_TIMED_OUT 

我怎樣才能顯示正確的信息給用戶,讓他/她知道確切的錯誤是什麼?

+4

的可能的複製[在角$ http服務,我怎麼能捕獲錯誤的 「地位」?](http://stackoverflow.com/questions/27507678/in-angular-http-service-how-can-i-catch-the-status-of-error) –

+0

更好的使用try/catch throw的方法 – amoeba

+0

爲什麼是@amoeba? – maurycy

回答

0

您可以使用http響應代碼創建一個對象並鏈接一條消息。要拋出這些錯誤,你可以使用攔截器。

moduleError.factory('HttpErrorHandler', function(){ 
    return { 
     401: 'You are not logged in', 
     403: 'You do not have permissions' 
    } 
}); 



$httpProvider.interceptors.push(function($q, HttpErrorHandler) { 
    return { 
    'responseError': function(rejection) { 
     console.log(HttpErrorHandler[rejection.status]); 
    }; 
}); 

如果錯誤與此操作有關,請在啓動時啓動錯誤。您可以將錯誤代碼400與身體中的對象一起扔出,例如:

{ 
    code: 30002, //Thats your custom code 
    message: 'My custom error message' 
} 

dossierService.getDossier(uid) 

.then(function (result) { 

    vm.dossier = result.dossier; 

}, function (error) { 

    if(error.status == 400){ 
     var my_error = JSON.parse(error.data); 
     console.log(my_error.message); 
    } 

}); 

我認爲這是一個很好的方法。

+0

我認爲這是一個很好的答案,但很糟糕的解釋哈哈。請解釋您可以在哪裏訪問錯誤對象,可能使用console.log語句來執行此操作。我也相信這是一種通用的方法來處理所有http錯誤,而不必在每次都拒絕承諾時處理它們。請確認Serginho – danday74

+0

謝謝@ danday74 – Serginho

0
$http.post("/path", {data:"data"}).then(function(response){ 
    // do something with success response 
}).catch(function(error) { 

    console.log(JSON.stringify(error)); 
    $scope.myerror=error 

}); 

,並在您的視圖...

<div ng-if="myerror!=null"> 
    {{myerror}} OR {{myerror.message}} 
</div>