Angular中的通用错误处理 [英] Generic error handling in Angular
问题描述
当服务中断时,我在我的应用程序中使用拦截器进行一般性错误处理 即使我更改了基本URL来测试我的服务,我仍收到状态为200的成功响应.我在做什么错??
I am using interceptor in my app for generic error handling when service is down I am getting success response with status 200 even i have changed the base url to test my service. What am i doing wrong??
var myServices = angular.module('myServices', ['ngResource']);
myServices.config(function ($provide, $httpProvider) {
$provide.factory('ErrorInterceptor', function ($q) {
return {
response: function(){
return response;// always success??
}
responseError: function(rejection) {
$scope.addErrorAlert("Services are currently not responding. Please try again later.",true);
return;
}
};
});
推荐答案
您可以使用拦截器编写全局异常处理程序.您只需要重写responseError拦截器即可.在这里,我在$ rootScope上定义了"openErrorModel"方法,以在有错误时打开带有错误消息的错误模型. 这将是更清洁和模块化的.这样就可以避免重复.
You can use interceptors to write global exception handler. You just need to override responseError interceptor. Here i called "openErrorModel" method defined on $rootScope to open error model with error message when ever there is error. This would be cleaner and modularized. and you can avoid duplication this way.
示例代码:
(function (global) {
"use strict";
angular.module("TestAPp").factory('httpInterceptor', ["$rootScope", "$q", function ($rootScope, $q) {
return {
responseError: function (response) {
/* Open Error model and display error */
$rootScope.openErrorModel(response);
/* reject deffered object so that it'll reach error block , else it'll execute success function */
return $q.reject(response);
}
};
}]);
}(this));
//注册代理人
(function (global) {
"use strict";
angular.module("TestApp", [])
.config([ '$httpProvider',function ($httpProvider) {
/* Register the interceptor */
$httpProvider.interceptors.push('httpInterceptor');
}]);
}(this));
PS:我的openErrorModel定义
PS: My openErrorModel definition
$rootScope.openErrorModel = function (error) {
$rootScope.errorMessage = error.data;
$('#errorModal').modal('show');
};
您可以参考角度处理错误有关更多信息.
You can refer to Error Handling in angular for more info.
这篇关于Angular中的通用错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!