预期的错误是我预期甚至在代码中自己提出的服务器中的错误.例如,当用户尝试执行他没有足够权限的操作时,我会使用描述错误的消息引发PermissionError(自定义异常).
我一直在寻找一种处理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 */ });
我有另一种方法,我不确定.基本上,不是将预期错误的消息打包成JSON对象,而是在我的django代码中,我将返回HttpResponse(content =“没有足够的权限”,status = 403).客户端jQuery将被修改如下:
ajaxResponse.done(function(response_data) { /* no error,do something */ }); ajaxResponse.fail(function(jqXHR,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状态代码.无论如何,我想知道哪一个是正确的方法.如果两者都没有,请分享你会做什么.
解决方法
有这样的全局配置 –
$.ajaxSetup({ error: function(xhr){ /* Do something with xhr.responseText */ window.status='Your error message goes here'; } });
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。