在我当前的angularJS中,我处理了错误,每当发生错误时,都会通过一个错误消息味精,但是我不需要这样:
我想在400 (Bad Request)
错误时通过“ 您提交的数据已存在,请尝试使用其他数据”之类的消息
,当net::ERR_CONNECTION_REFUSED
时,它应该像“您没有与互联网连接”一样通过msg
这里是我当前的片段:
$scope.formModel = {}; // It will post data and handle both success and error,
$scope.onSubmit = function () {
$http.post('http://127.0.0.1:8000/api/v1/contact/', $scope.formModel)
.then(function(response){
$scope.successPost = 'You have successfully submitted your Contact';
$timeout(function(){
$scope.successPost = '';
},4000);
$scope.contacts.push(response.data);
}, function(response){
$scope.errorPost = 'Ooops! An Error Ocuured saving your contact, please try again later';
$timeout(function(){
$scope.errorPost = '';
},6000);
});
$scope.formModel = {};
$scope.addContactForm.$setPristine();
};
在上述代码段中,遇到任何类型的错误都会出错,但是我需要自定义确切发生了什么错误,我该怎么办?
答案 0 :(得分:0)
状态由status
对象的response
属性提供。
状态消息作为statusText
对象的response
属性提供。
$scope.formModel = {}; // It will post data and handle both success and error,
$scope.onSubmit = function () {
$http.post('http://127.0.0.1:8000/api/v1/contact/', $scope.formModel)
.then(function(response){
$scope.successPost = 'You have successfully submitted your Contact';
$timeout(function(){
$scope.successPost = '';
},4000);
$scope.contacts.push(response.data);
}, function(response){
$scope.errorPost = 'Ooops! An Error Ocuured saving your contact, please try again later';
if (response.status == 400) {
$scope.errorPost = "Your submitted data already exist, please try with another data";
};
if (response.status == 500) {
$scope.errorPost = "You are not connected with internet";
});
console.log("Error status",response.status);
console.log("Error message",response.statusText);
$timeout(function(){
$scope.errorPost = '';
},6000);
});
$scope.formModel = {};
$scope.addContactForm.$setPristine();
};
从文档中:
response
对象具有以下属性:
- 数据 –
{string|Object}
–使用转换函数转换的响应主体。- 状态 –
{number}
–响应的HTTP状态代码。- 标题 –
{function([headerName])}
–标题获取器功能。- config –
{Object}
–用于生成请求的配置对象。- statusText –
{string}
–响应的HTTP状态文本。- xhrStatus –
li>{string}
– XMLHttpRequest的状态(complete
,error
,timeout
或abort
)。
有关更多信息,请参见