预期错误是我在代码中预期甚至自己提出的来自服务器的错误。例如,当用户尝试执行他没有足够权限的操作时,我会提出PermissionError
(一个习俗Exception
)并带有描述错误的消息。
我一直在寻找一种好方法来处理 AJAX 情况下的预期错误。唯一的要求是能够向用户显示错误消息,因为我想让我的用户了解正在发生的事情。
我目前的做法是将错误消息打包成 JSON 对象并将其发送回客户端
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 */
});
我想到了另一种方法,但我不确定。基本上,在我的 django 代码中,我不会将预期错误消息打包到 JSON 对象中,而是返回HttpResponse(content="no sufficient privilege", status=403)
。客户端 jQuery 将进行如下修改:
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 状态代码不应该这样使用。无论如何,我想知道哪一种是正确的方法。如果两者都不是,请分享您会做什么。