我有服务,提出发布请求并返回数据。
app.service('flagService', ['$http', function ($http) {
this.getData = function (r, c) {
return $http.post('http://localhost:8080/api/flag', { row: r, column: c }).then(function (data) {
return data;
})
}
}]);
在控制器的某个地方
flagService.getData(row, column).then(function () {
console.log('it works')
})
但是api也可以返回500状态代码。在这种情况下,我在控制台中得到“可能未处理的拒绝......”。现在我想简单alert()
,当返回500错误时将打开它。我尝试了很多很多解决方案,包括第二个函数.catch()
,.error()
。
app.service('flagService', ['$http', function ($http) {
this.getData = function (r, c) {
return $http.post('http://localhost:8080/api/flag', { row: r, column: c }).then(function (data) {
return data;
}, function (error) {
console.log(error)
}).catch(function () {console.log('error')}).error(function() {console.log('error')})
}
}]);
但我仍然无法忍受错误。有解决方案吗谢谢!
答案 0 :(得分:0)
您可以使用拦截器进行全局错误处理,只要拒绝解决请求,就会调用responseError。
.factory('myInterceptor', ['$q', '$location', '$injector', function ($q, $location, $injector) {
return {
response: function (response) {
return response || $q.when(response);
},
responseError: function (rejection) {
if (rejection.status === 500) {
console.log('http 500 response')
}
return $q.reject(rejection);
}
}
}])
.config(['$httpProvider', function ($httpProvider) {
$httpProvider.interceptors.push('myInterceptor');
}]);