我使用Django Rest Framework构建的API。
我的数据库中只有四个字段。
他们是userid, name, email, phone
我在此代码段下面编写了代码,它可以很好地处理错误和成功:
$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! It seems Your Submitted User ID or Phone Number or Email are already exist, please try again with different data';
$timeout(function(){
$scope.errorPost = '';
},10000);
});
$scope.formModel = {};
$scope.addContactForm.$setPristine();
};
我的后端不允许发布任何重复的项目,例如数据库中是否存在电话号码,这是用户第二次无法发布,如果他们尝试发布已经存在的电话号码,我想向他们显示“您提交的电话号码已经存在”的消息同样,如果他尝试提交已经存在的电子邮件,我想向他显示“您提交的电话已经存在”的消息“
当前,我的代码段的工作方式就像他可以成功发布,获得成功消息,并且如果有错误,则得到错误消息,但我想确切地显示发生了什么以及为什么不被接受。
答案 0 :(得分:-1)
我将查看响应中返回的特定错误,然后基于该消息,我将显示适当的消息。如果服务器未返回其他消息,则我将首先更正该问题。如果不能,则可能需要实现更多的客户端逻辑,例如在用户填写表单并将其设置为只读或类似值之前查看是否存在任何值。
function(response){
//could use case statements too instead of if statements.
if(response.cantRememberVarName == "user id already exists"){
$scope.errorPost = "Ooops User Id already exists";
}
if(response.cantRemberVarName == "phone number already exists"){
....
}
$scope.errorPost = 'Ooops! It seems Your Submitted User ID or Phone Number or Email are already exist, please try again with different data';
$timeout(function(){
$scope.errorPost = '';
},10000);
});