【发布时间】:2012-09-25 22:17:29
【问题描述】:
我们有一个 API,它使用正确的 HTTP 状态代码来处理错误,并使用 JSON 编码的响应和适当的 Content-Type 标头进行响应。我的情况是jQuery.ajax()在遇到HTTP错误状态时触发error回调,而不是success回调,所以即使我们有一个可理解的JSON响应,我们也必须求助于这样的东西:
$.ajax({
// ...
success: function(response) {
if (response.success) {
console.log('Success!');
console.log(response.data);
} else {
console.log('Failure!');
console.log(response.error);
}
},
error: function(xhr, status, text) {
var response = $.parseJSON(xhr.responseText);
console.log('Failure!');
if (response) {
console.log(response.error);
} else {
// This would mean an invalid response from the server - maybe the site went down or whatever...
}
}
});
有没有比在每个jQuery.ajax() 调用中的两个位置进行相同错误处理更好的范例?它不是很干,我敢肯定我只是在这些情况下错过了一些关于良好错误处理实践的东西。
【问题讨论】:
-
我假设 HTTP 状态代码,您的意思是您在出错时将 501 作为 HTTP 状态代码发回。如果您在服务器端正确处理错误,为什么要这样做?
-
查看 jquery.ajax (api.jquery.com/jQuery.ajax) statusCode 参数。
-
@LawrenceJohnson:我正在使用响应代码,因为它们本来就是要使用的。发送 200 OK 每个响应都需要重新发明关于错误代码/消息的轮子。
-
是的,但是这些错误在网络级别的协议中。如果您认为验证错误与 Http 错误相同,那您就大错特错了。
-
@Liam:我的问题与如何从 jQuery.ajax() 中获取响应代码无关。
标签: jquery ajax error-handling