我想在我的 JavaScript 代码中实现重试逻辑。这就是我调用 API 的方式:
$.ajax({
url: api_url + 'report',
type: 'GET',
dataType: 'json',
async: false,
tryCount : 0,
retryLimit : 3,
headers: {
"Authorization": "Basic " + btoa(api_username + ":" + api_pass)
},
data: {start: start_date, end: end_date},
success: function(result) {
data = result.results;
console.log("success");
},
error : function(xhr, textStatus, errorThrown ) {
console.log("in error");
if (textStatus == 'timeout') {
this.tryCount++;
if (this.tryCount <= this.retryLimit) {
//try again
console.log("try count:");
console.log(this.tryCount);
$.ajax(this);
return;
}
return;
}
if (xhr.status == 500) {
console.log("still 500");
} else {
console.log("still !500");
}
}
});
因此,当服务器出现问题并且返回 http 500 时,我在上述 JS 文件中的控制仍然不会进入“error:” block ,并且这一行:“console.log("in error") ;”没有打印在控制台上。
如何在我的代码中正确实现重试逻辑,以防我的服务器返回 500 然后它应该继续重试 x 次?
最佳答案
500错误通常意味着后端服务器出现问题。所以它不会进入客户端 JavaScript 的错误 block 。我认为你无能为力。但一般来说,您总是可以要求后端开发人员进行更好的错误处理,并在可能的情况下返回适当的错误响应。
关于javascript - 如果 API 服务器返回 http 500,AJAX 调用不会进入 "error:" block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37781288/