AngularJS全局错误处理 - 自定义方法错误处理程序不会触发

时间:2016-06-29 09:59:33

标签: angularjs

这里是场景(AngularJS v1.3.15):

$httpProvider.interceptors.push(function($rootScope) {
  return {
    'responseError': function(rejection) {          
               //...some custom data checking

               console.log('error #1');
               return rejection;
           }
     };
});

现在,我使用$resource(返回404错误,在这种情况下需要)将查询发送到服务器,然后我返回$promise

var promise = controller.sendCustomQuery();

promise.catch(function (response) {
                 console.log('error #2');
               }
             );

并且在控制台中我只能看到消息error #1而没有error #2。为什么?

2 个答案:

答案 0 :(得分:1)

确保你从basePath: './', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['jspm', 'mocha', 'chai-as-promised', 'chai', 'sinon'], // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: ['Chrome'], // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['mocha'], // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: true, // enable / disable colors in the output (reporters and logs) colors: true, // list of files / patterns to load in the browser files: [], jspm: { // Edit this to your needs config: 'jspm.config.js', packages: 'client/jspm_packages', loadFiles: [ 'client/js/common/services/**/*.spec.js' ], serveFiles: [ 'client/js/**/*.js', 'client/js/**/*.html', 'client/js/**/*.css' ], paths: { 'github:*': 'base/client/jspm_packages/github/*', 'npm:*': 'base/client/jspm_packages/npm/*', 'js/*': 'base/client/js/*' }, urlRoot: './' }, proxies: { '/client': '/base/client' }, // list of files to exclude exclude: [], // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, client: { captureConsole: true, mocha: { bail: false, // require: 'should' reporter: 'spec', ui: 'bdd' } } 函数中抛出/拒绝:

responseError

如果您只是有效地处理异常(恢复),那么您将不会在链中的下一步中捕获。

答案 1 :(得分:1)

而不是返回拒绝本身返回拒绝承诺

angular.module('app', [])
  .config(function($httpProvider) {
    $httpProvider.interceptors.push(function($q) {
      return {
        responseError: function(rejection) {
          console.log('error #1')
          return $q.reject(rejection)
        }
      }
    })
  })
  .run(function($http) {
    $http.get('some/error/path').catch(function() {
      console.log('error #2')
    })
  })
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<div ng-app='app'>

</div>