我们有一个 API,它使用正确的 HTTP 状态代码来处理错误,并使用 JSON 编码的响应和适当的 Content-Type
header 进行响应。我的情况是 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()
调用中的两个位置执行相同的错误处理更好的范例?它不是很干燥,而且我确信我在这些情况下错过了一些关于良好错误处理实践的东西。
最佳答案
它捕获全局 Ajax 错误,您可以通过多种方式处理这些错误:
if (jqXHR.status == 500) {
// Server side error
} else if (jqXHR.status == 404) {
// Not found
} else if {
...
或者,您可以自己创建一个全局错误处理程序对象并选择是否调用它:
function handleAjaxError(jqXHR, textStatus, errorThrown) {
// do something
}
$.ajax({
...
success: function() { ... },
error: handleAjaxError
});
关于jQuery AJAX 错误处理(HTTP 状态代码),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12734714/