[英]Spring Boot & AngularJS / global exception handler
我是AngularJS的新手,並且希望通過最佳實踐在REST應用程序上實現全局異常處理程序。
Spring全局異常處理程序:
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Throwable.class)
public void defaultErrorHandler(HttpServletRequest req, Throwable exp) {
// redirect and bind exception to error.html
}
}
例如在Angular控制器上,我在引發NPE
Spring控制器上調用$http.get
請求。
如何將捕獲的異常對象綁定到error.html
?
為了解決這個問題,我們將不得不添加一個服務/工廠來攔截http調用。 您可以在配置中像這樣
$httpProvider.interceptors.push('httpRequestInterceptor');
現在,以上服務將是這樣的
angular.module("app").factory('httpRequestInterceptor', function ($q) {
return {
'request': function (config) {
// Extract request information
return config || $q.when(config);
},
'responseError': function(rejection) {
// Extract response error information and handle errors
return $q.reject(rejection);
}
}
});
在響應錯誤信息塊中,您可以重定向到error.html頁面。
以下方法對我有用。
myApp.factory('responseObserver',
function responseObserver($q, $window, $rootScope) {
return function (promise) {
return promise.then(function (successResponse) {
return successResponse;
}, function (errorResponse) {
switch (errorResponse.status) {
//server error
case 500:
$rootScope.redirectToErrorPage();
break;
//If unauthorized
case 401:
$rootScope.logout();
break;
}
return $q.reject(errorResponse);
});
};
});
myApp.config(function($stateProvider, $httpProvider) {
$httpProvider.responseInterceptors.push('responseObserver');
$stateProvider
.state('login', {
url: '/login',
templateUrl: 'templates/login.html',
controller: 'LoginController'
})
.state('error', {
url: '/error',
templateUrl: 'templates/error.html'
})
});
myApp.run(['$rootScope', '$state', function ($rootScope, $state) {
$rootScope.redirectToErrorPage = function()
{
$state.transitionTo("error");
}
$rootScope.logout = function()
{
$state.transitionTo("login");
}
}]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.