我试图在我的角应用程序中捕获例如500的服务器错误。不幸的是,这种结构失败了:
return promise = this.httpService.jsonp("serverurl")
.success((response: any): ng.IPromise<any> => { return response.data; })
.error((response: any): ng.IPromise<any> => { return response.data; });
我想捕获服务器响应 - 在这种情况下只是消息。怎么做?
答案 0 :(得分:1)
$ http服务是一个函数,它接受一个参数 - 一个配置对象 - 用于生成HTTP请求并返回一个promise。
// Simple GET request example:
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
console.log(response); // add console log of response
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
console.log(response); // add console log of error response
});
或者拦截器可用于监视&#34;所有的http:
// register the interceptor as a service
$provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
return {
// optional method
'request': function(config) {
// do something on success
return config;
},
// optional method
'requestError': function(rejection) {
// do something on error
if (response.status === 500) {
//DO WHAT YOU WANT
}
return $q.reject(rejection);
},
// optional method
'response': function(response) {
// do something on success
return response;
},
// optional method
'responseError': function(rejection) {
// do something on error
if (response.status === 500) {
//DO WHAT YOU WANT
}
return $q.reject(rejection);
}
};
});
$httpProvider.interceptors.push('myHttpInterceptor');