Angular 中的通用错误处理 [英] Generic error handling in Angular

查看:32
本文介绍了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');
};

您可以参考Angular 中的错误处理 了解更多信息.

You can refer to Error Handling in angular for more info.

这篇关于Angular 中的通用错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆