[英]How to catch/handle backend exceptions in AngularJS
我正在嘗試通過使用Spring MVC-Spring Security-AngularJS構建一個小型Web應用程序來學習AngularJS。 我的UserDetailsService在登錄時會引發UserNotFoundException。但是我不知道如何在Angular中處理異常。 我曾嘗試過使用google,但找不到有關異常處理的簡單,完整的示例。
這是我的身份驗證角度模塊的一部分:
$http.get('user', {
headers : headers
}).success(function(data) {
if (data.name) {
auth.authenticated = true;
} else {
auth.authenticated = false;
}
callback && callback(auth.authenticated);
$location.path(auth.path==auth.loginPath ? auth.homePath : auth.path);
}).error(function() {
auth.authenticated = false;
callback && callback(false);
});
如何在錯誤回調函數中到達並捕獲此特定的UserNotFoundException?
我建議在控制器中創建@ExceptionHandler
,並在UserNotFoundException
添加另外兩個字段( errorMessage
和errorCode
)。 然后在您的角度回調中,您可以檢查哪個是errorCode
號。
好文章:
對於高級錯誤處理,我建議采用以下行為: https : //github.com/jirutka/spring-rest-exception-handler
這是一個與您的案例有關的樣本提琴: http : //jsfiddle.net/bkUEu/1044/
在您的應用程序angularjs中嘗試使用此
$http.get('user', {
headers : headers
}).then(function(data) {
if (data.name) {
auth.authenticated = true;
} else {
auth.authenticated = false;
}
callback && callback(auth.authenticated);
$location.path(auth.path==auth.loginPath ? auth.homePath : auth.path);
}).catch(function() {
auth.authenticated = false;
callback && callback(false);
});
使用then和catch函數,而不是成功和錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.