2016-09-29 77 views
0

我正在用离子建立一个应用程序,我想处理发生在$ http()AJAX调用中的500内部服务器错误。是否有可能创建任何拦截器来处理?在AngularJS中处理HTTP 500内部服务器错误

这里是我的控制器代码:如果用户输入一些无效的投入和服务器无法处理它抛出500内部服务器错误

.controller('RegistrationController',function($scope,$http){ 
    $scope.doRegistration = function(){ 
      $http({ 
       method : "POST", 
       url : BASE_URL, 
       params : { 
         //sending the parameters as JSON 
       } 
      }).then(function successCallback(response){ 
       if(response.status == 200) 
        //handling the response sent by server 
      },function errorCallback()}); 
    }; 
}); 

。当进行AJAX调用时,我显示一个微调,当发生一些服务器错误时,我应该停止AJAX调用并停止微调,并向用户显示一些弹出窗口,说“遇到的服务器错误”。

回答

2
'use strict'; 

angular.module('myApp').factory('MyService', function ($http, $q) { 

var BASE_URL = 'some.url.com'; 

function register() { 

    var defer = $q.defer(); 

    $http({method: "POST", url: BASE_URL, params: {}}) 
    .then(function (response) { 
     defer.resolve(response.data); 
    }) 
    .catch(function (reason) { 
     defer.resolve(reason); 
    }); 

return defer.promise; 
} 


return { 
register: register 
} 

}).controller('MyController', function ($scope, MyService) { 

    MyService.register().then(function (response) { 
    // success 
    }).catch(function (reason) { 
    // err 
    if (reason.status === 500) { 
     // do something 
     $scope.spinner = false; 
     console.log('Encountered server error'); 
    } 
    }); 
}); 
0

您可以创建拦截如下 -

app.factory('testResponseInterceptor', function ($q ,$rootScope,$location) { 
return { 
    response: function (response) { 
     //correct response 
     return response; 
    }, 
    responseError: function (response) { 
     //error in response 
    } 
    }; 
}); 

和你的模块中进行配置 -

app.config(function ($httpProvider) { 
    $httpProvider.interceptors.push('testResponseInterceptor'); 
});