[英]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.