[英]Nodejs HTTP Retry Pattern
JS新手在這里。 我正在嘗試使用內置的 https lib 的請求方法(我必須做一個 POST)來實現重試邏輯。 也在 Azure 函數中實現它。
編輯我已經修改了代碼,它會重試 HTTP 錯誤,但不會重試套接字或連接錯誤。 Doc說,如果發生套接字錯誤,將首先調用 on('socket') 然后調用 on('error')。 但是當出現 ECONNRESET 或 ETIMEDOUT 錯誤時,我的應用程序永遠不會重試。
async function fetchWithRetry(options, reqBody,context) {
return new Promise((resolve, reject) => {
let attempts = 1;
const fetch_retry = (options, n) => {
let httpsReq = httpsClient.request(options, function (res) {
const code = res.statusCode;
const message = res.statusMessage;
if (n === 0) {
reject({
'status': code,
'message': message
});
} else if (code < 200 || code >= 300) {
context.log("Retry again: Got back code: " + code + " message: " + message);
context.log("With delay " + attempts * delay);
setTimeout(() => {
attempts++;
fetch_retry(options, n - 1);
}, attempts * delay);
} else if (code === 201) {
resolve({
'status': code,
'message': message
});
} else {
var body = '';
res.on('data', function (chunk) {
body = body + chunk;
});
res.on('end', function () {
resolve(JSON.parse(body));
});
}
httpsReq.on('error', function (error) {
context.log("Retry again: Got back code: " + code + " message: " + message + " error: " + error);
context.log("With delay " + attempts * delay);
setTimeout(() => {
attempts++;
fetch_retry(options, n - 1);
}, attempts * delay);
});
});
httpsReq.write(reqBody);
httpsReq.end();
};
return fetch_retry(options, numberOfRetries);
});
}
當發生錯誤時,代碼調用 end() 並且我的 function 死掉了。 我可以請一些幫助來解決它。 還嘗試將其包裹在 promise 周圍,因為這是最佳實踐。
而不是return resolve(json);
只需resolve(json);
, 而不是throw reject(json);
只是reject(json);
找到解決方案,在請求錯誤處理程序而不是響應上捕獲套接字錯誤
`Req.on('error', function (error) {
context.log("Retry again: " + error);
context.log("With delay " + attempts * delay);
setTimeout(() => {
attempts++;
fetch_retry(options, n - 1);
}, attempts * delay);
});`
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.