几次尝试后,Node.js请求抛出ECONNREFUSED

时间:2019-01-25 12:02:49

标签: node.js amazon-ec2 aws-lambda requestjs

我正在使用以下代码:

async function validateMOData(data, callback) {
    success('Validation started');
    let a = 0;
    let i = data.length;
    console.log('length of array', i);
    while (i--) {
        a = a + 1;
        console.log('Loop Count', a);
        console.log(data[i]);
        let result;
        try {
            result = await checkValidity(data[i]);
            if ((JSON.parse(result.body)).isValid === false) {
                createErrorLog(data[i].MemberId, data[i].MemberAgreementId, (JSON.parse(result.body)).responseMessage, (JSON.parse(result.body)).responseCode, 'x', data[i].CsvFileName)
                deleteFaultyData(data[i].Id);
                data.splice(i, 1);
            }
        } catch (err) {
            console.log(err);
        }
    }
    success('validation ended');
    callback(data);
}
function checkValidity(record) {
    return new Promise((resolve, reject) => {
        let validityCheckUrl = `${constants.USER_INTERFACE.SERVER_URL_PREFIX}validateMemberData/?memberId=${record.MemberId}&memberAgreementId=${record.MemberAgreementId}`;
        request({ url: validityCheckUrl, pool: { maxSockets: 10 } }, (error, response, body) => {
            if (error) {
                reject(error);
            } else {
                resolve(response, body);
            }
        });
    });

}

在while循环中进行几次迭代后,checkValidity方法开始引发以下错误:

{ Error: connect ECONNREFUSED IP:port
at Object._errnoException (util.js:1022:11)
at _exceptionWithHostPort (util.js:1044:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1198:14)
code: 'ECONNREFUSED',
errno: 'ECONNREFUSED',
syscall: 'connect',
address: 'IP',
port: port }

此错误不是在第一个请求中出现,而是在一些请求之后。有人可以帮忙吗?我想念什么吗?

注释:此代码在AWS lambda上运行,并且checkValidity连接到部署在EC2上的Node.js服务器

1 个答案:

答案 0 :(得分:0)

我认为您没有放置检查以检查 i 是否为负或简单地说在try内没有中断条件

try {
      ***********************
        result = await checkValidity(data[i]);
        if ((JSON.parse(result.body)).isValid === false) {
            createErrorLog(data[i].MemberId, data[i].MemberAgreementId, (JSON.parse(result.body)).responseMessage, (JSON.parse(result.body)).responseCode, 'x', data[i].CsvFileName)
            deleteFaultyData(data[i].Id);
            data.splice(i, 1);
        }
    } catch (err) {
        console.log(err);
    }

因此循环将尝试在checkvalidity内部发送数据,该数据甚至不存在,因此很可能是发送错误