问题描述
我知道如何接收服务器数据或错误.有很多方法.例如:
I know how to receive server data or error. There are many ways. For example:
$.ajax({
type: "get",
url: "/widgets/",
success: function (data, text) {
console.log('this is a data');
},
error: function (request, status, error) {
console.log('this is an error');
}
});
请看这张图片:
我有我的错误功能,我在那里做我需要的.如何防止第一行出错.我已经测试了 4xx 和 5xx 错误,但没有区别.我知道当开发者控制台隐藏时,最终用户不会看到这个错误.
I have my error function and I do what I need there.How can I prevent error in the first line.I have tested 4xx and 5xx errors but no difference.I know that end user does not see this error when developer console is hidden.
我需要这个来设计 API.我知道我可以从服务器发送 200 个响应,并带有一个额外的参数,表明这是一个错误或成功的结果.
I need this to design an API.I know that I can send 200 responses from server with an additional argument that show that this is an error or a success result.
但是如果我可以发送 4xx 或 5xx 响应,则不需要额外的参数.这种方式对我来说有一些额外的收获.例如,我可以将成功结果应用于我的客户端模型,而无需担心额外的参数.
But if I can send 4xx or 5xx responses then there is no need to extra argument.This way has some additional gains for me. For example I can apply success result to my client side models without worry about additional args.
谢谢
推荐答案
AFAIK 在返回错误状态代码 (4xx, 5xx) 时,您无法让红色的东西消失.浏览器使用它们来指示某些事情可能没有按预期进行.这些仍然只是装饰品,因为 4xx 和 5xx 状态代码是完全有效的,所以我看不出你有什么想要消除它们的理由.
AFAIK you cannot make the red thingies go away, when returning error status-codes (4xx, 5xx). They are used by the browser to indicate that something might have not gone as expected. Still these are mere decorations, since 4xx and 5xx status codes are perfectly valid, so I don't see a reason for you wanting to eliminate them.
正如您自己所说,您的另一种选择是发送来自服务器的 200 个响应,并带有一个附加参数,表明这是一个错误或成功结果".
As you said yourself, your other alternative would be sending "200 responses from server with an additional argument that show that this is an error or a success result".
我当然建议您使用 4xx 和 5xx 代码(这就是它们的设计目的)并且不要担心浏览器在开发者控制台中的提示警告(也就是红色的东西).
I certainly recommend using the 4xx and 5xx codes though (that's what they are designed for) and stop worrying about browser's heads-up warnings in developer console (aka red thingies).
另见这个 和 this 问题在获取其他类型时引用了类似的错误资源(图像、文件等).您看到的错误实际上具有相同的性质.
See also this and this questions that refer to similar errors when fetching other kinds of resources (images, files etc). The errors you see are actually of the same nature.
这篇关于防止未处理的 jQuery AJAX 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!