首页 > 解决方案 > Nodejs HTTP 重试模式

问题描述

JS新手来了!我正在尝试使用内置的 https lib 的请求方法(我必须做一个 POST)来实现重试逻辑。还在 Azure Functions 中实现它。

编辑 我已经修改了代码,它重试了 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() 并且我的函数终止。我可以请一些帮助来解决它。还试图将它包装在一个承诺周围,因为这是最佳实践。

标签: javascriptnode.jsazurehttpsazure-functions

解决方案


而不是return resolve(json);just resolve(json);,而不是throw reject(json);justreject(json);


推荐阅读