[英]How to catch/handle backend exceptions in AngularJS
I am trying to learn AngularJS by building a small webapp with Spring MVC-Spring Security-AngularJS. 我正在尝试通过使用Spring MVC-Spring Security-AngularJS构建一个小型Web应用程序来学习AngularJS。 My UserDetailsService throws a UserNotFoundException while logging in. But i don't know how to handle exceptions in Angular.
我的UserDetailsService在登录时会引发UserNotFoundException。但是我不知道如何在Angular中处理异常。 I have tried to google but could not find simple, complete examples about exception handling.
我曾尝试过使用google,但找不到有关异常处理的简单,完整的示例。
This is a part of my authentication angular module: 这是我的身份验证角度模块的一部分:
$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);
});
How can i reach and catch this specific UserNotFoundException inside the error callback function? 如何在错误回调函数中到达并捕获此特定的UserNotFoundException?
What i suggest is to create @ExceptionHandler
in your controller and in your UserNotFoundException
add two more fields ( errorMessage
and errorCode
) for example. 我建议在控制器中创建
@ExceptionHandler
,并在UserNotFoundException
添加另外两个字段( errorMessage
和errorCode
)。 then in your angular callback you can check which is the errorCode
number. 然后在您的角度回调中,您可以检查哪个是
errorCode
号。
Good articles: 好文章:
For advanced error handling I recommend this behaviour : https://github.com/jirutka/spring-rest-exception-handler 对于高级错误处理,我建议采用以下行为: https : //github.com/jirutka/spring-rest-exception-handler
Here is a sample fiddle with your case: http://jsfiddle.net/bkUEu/1044/ 这是一个与您的案例有关的样本提琴: http : //jsfiddle.net/bkUEu/1044/
In your application angularjs try to use this 在您的应用程序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);
});
Use then and catch function instead of success and error. 使用then和catch函数,而不是成功和错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.