AngularJS中的错误处理:http get然后construct
Error handling in AngularJS http get then construct
如何处理HTTP错误,例如500,当使用AngularJS的" HTTP get then"构造(promises)?
$http.get(url).then(
function(response) {
console.log('get',response)
}
)
问题是,对于任何非200 HTTP响应,不调用内部函数
您需要添加一个额外的参数:
$http.get(url).then(
function(response) {
console.log('get',response)
},
function(data) {
// Handle error here
})
可以使用:
$http.get(url)
.then(function (response) {
console.log('get',response)
})
.catch(function (data) {
// Handle error here
});
类似于@this。Lau_答案,不同的方法。
https://docs.angularjs.org/api/ng/service/http美元
$http.get(url).success(successCallback).error(errorCallback);
用你的函数替换successCallback和errorCallback
编辑:考虑到他使用的是then
, Laurent的答案更正确。但我还是把这个留到这里,作为将来访问这个问题的人的一个选择。
如果你想全局处理服务器错误,你可能需要为$httpProvider:
注册一个拦截器服务$httpProvider.interceptors.push(function ($q) {
return {
'responseError': function (rejection) {
// do something on error
if (canRecover(rejection)) {
return responseOrNewPromise
}
return $q.reject(rejection);
}
};
});
文档: http://docs.angularjs.org/api/ng http美元。
试试这个
function sendRequest(method, url, payload, done){
var datatype = (method === "JSONP")? "jsonp" : "json";
$http({
method: method,
url: url,
dataType: datatype,
data: payload || {},
cache: true,
timeout: 1000 * 60 * 10
}).then(
function(res){
done(null, res.data); // server response
},
function(res){
responseHandler(res, done);
}
);
}
function responseHandler(res, done){
switch(res.status){
default: done(res.status + ": " + res.statusText);
}
}
我真的不能用上面的工作。所以这可能对某人有帮助。
$http.get(url)
.then(
function(response) {
console.log('get',response)
}
).catch(
function(response) {
console.log('return code: ' + response.status);
}
)
参见$http response
参数
相关文章:
- 如何将PHP get查询转换为Meteor's HTTP.get()
- Angularjs http.get() Cross-Origin 请求被阻止
- Angular js http get返回所有页面
- Angular.js-$http.get-使用文件中的缓存
- 当我在chrome中切换设备模式时,$http.get请求失败
- Angular http.get没有'我不喜欢在开头和结尾加方括号的文本文件
- 从javaspring方法管理http.get响应
- 我可以在React应用程序中使用什么作为Angular的等价物;s$http.get
- 如何让foreach循环等待$http.get完成后再继续
- Angular Cross Origin Request CORS失败,但节点http.get()成功返回
- 使用$http.get()-OAuth身份验证下载带有Angular的远程文件
- $http GET URL更改并查找错误的资源
- angularJS $http.get communicating with API
- 在AngularJS中使用$http.get检索JSON时出现错误400
- AngularJS $http GET 请求到本地 JSON 文件返回语法错误:意外令牌]
- 使用角度$http.get从服务器下载文件
- AngularJS或JQuery解析错误格式的JSON(http get)
- AngularJS HTTP Get 没有得到响应
- 无法在角度 js 中将参数传递给 http get 请求
- Meteor:使用HTTP.get从客户端访问网站(CORS错误)