这是预期的错误是从我的预期,甚至在code提出自己的服务器。例如,当用户试图执行为此,他没有足够的权限的行动,我会提高 PermissionError
(自定义异常
)与描述错误的消息。
An expected error is one from the server that I anticipated or even raised by myself in the code. For example, when a user attempts to perform an action for which he has no sufficient privilege, I would raise PermissionError
(a custom Exception
) with a message describing the error.
我一直在寻找一个很好的方式来处理预期的错误对AJAX的情况。唯一的要求是要能够显示错误信息给用户,因为我要保持我的用户在什么事情上的循环。
I have been searching for a good way to handle expected error for AJAX situation. The only requirement is to be able to display the error message to the user, as I want to keep my users in the loop of what's going on.
我目前的做法是包装错误消息成JSON对象并将其发送回客户端
My current approach is packaging the error message into a JSON object and send it back to the client-end
var ajaxResponse = $.ajax({
....
});
ajaxResponse.done(function(jsonObj) {
if (jsonObj.success) {
/* no error, do something */
}
else {
/* expected error returned, display jsonObj.error to user */
}
});
ajaxResponse.fail(function(jqXHR, textStatus, errorThrown) {
/* unexpected error returned */
});
我心目中的另一种方法,这我不知道。而不是包装预期的错误的消息成JSON对象,在我的Django code基本上,我将返回的Htt presponse(CONTENT =没有足够的权限,状态= 403)
。客户端的jQuery会被修改如下所示:
I have another approach in mind, which I am not sure about. Basically, instead of packaging the message of expected error into a JSON object, in my django code I would return HttpResponse(content="no sufficient privilege", status=403)
. The client-end jQuery would get modified like the following:
ajaxResponse.done(function(response_data) {
/* no error, do something */
});
ajaxResponse.fail(function(jqXHR, textStatus, errorThrown) {
/* both expected and unexpected error would end up here.
* It's an expected error when error code is 403 and
* jqXHR.responseText would give me the error message to
* display to the user.
*/
});
我喜欢第二种方法组中的所有错误,预期的或意外的,在一个地方。但后来,我有一种感觉,HTTP状态code不应该用这种方式。不管怎么说,我想知道哪一个是正确的道路要走。如果没有,请分享你会做什么。
I like how the second approach groups all errors, expected or unexpected, in one place. But then, I have a feeling that http status code shouldn't be used this way. Anyways, I want to know which one is the right way to go. If neither, please share what you would do.
有这样一个全局配置 -
Have a global configuration like this -
$.ajaxSetup({
error: function(xhr){
/* Do something with xhr.responseText */
window.status='Your error message goes here';
}
});