我想在我的应用程序中编写一个错误处理部分,我在下面使用此代码,但是当错误500发生时,它可以正常工作,但是有一个小问题,或者说是大问题,那就是页面在第一次加载时以及第二次错误页面加载之后,如何我删除了这几秒钟,直接进入错误页面,而没有加载发布错误的主页?有没有办法在执行其控制器后加载html模板?
var interceptor = ['$rootScope', '$q', function (scope, $q) {
function success(response) {
return response;
}
function error(response) {
var status = response.status;
if (status == 500) {
window.location= "http://www.domain.lan/#!/error";
return;
}
if (status == 403) {
// window.location = "dashboard";
return;
}
// otherwise
return $q.reject(responseInterceptors);
}
return function (promise) {
return promise.then(success, error);
}
}];
$httpProvider.responseInterceptors.push(interceptor);
我假设您正在使用角度ui路由器。
首先,您需要在$ stateProvider配置中添加一个状态以了解ui-router的“错误”状态。
路由配置代码
//added state to understand error
$stateProvider.state("error": {
url: "/error",
templateUrl: '/views/error.html',
controller: 'errorCtrl' //optional if you want any specific functionality
});
然后,您执行了window.location并设置了导致页面刷新的URL window.location。代替使用window.location使用window.location.hash
拦截功能变更
var interceptor = ['$rootScope', '$q', '$location', function (scope, $q, $location) {
function success(response) {
return response;
}
function error(response) {
var status = response.status;
if (status == 500) {
//window.location= "http://www.domain.lan/#!/error";
//window.location.hash= "/error"; //it will rewrite the url without refreshing page
$location.path('error');
return;
}
if (status == 403) {
// window.location = "dashboard";
return;
}
// otherwise
return $q.reject(responseInterceptors);
}
return function (promise) {
return promise.then(success, error);
}
}];
$httpProvider.responseInterceptors.push(interceptor);
其他方式,您可以尝试相同的$ state.go('error'); 不要忘记添加$ state依赖性。
希望对您有帮助。让我知道是否还有任何混乱。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句