Monday, 15 May 2017

node.js http GET - why isn't it returning to the calling function when an error is encountered?

Can someone please tell me why, when "reject on request error" is encountered, this function doesn't return anything to the function that I'm calling it from?

I want an error message returned to the function that calls this, but it appears the the code just stops executing when the indicated error is encountered.

function httpRequest(options, postData) {
console.log('DEBUG - httpRequest - begin');
return new Promise(function(resolve, reject) {
    console.log('DEBUG - httpRequest - a');
    var req = http.request(options, function(res) {
        console.log('DEBUG - httpRequest - b');
        // reject on bad status
        if (res.statusCode < 200 || res.statusCode >= 300) {
            console.log('DEBUG - httpRequest - error: bad status ' + res.statusCode);
            return reject(new Error('statusCode=' + res.statusCode));
        }
        // cumulate data
        var body = [];
        res.on('data', function(chunk) {
            body.push(chunk);
        });
        // resolve on end
        res.on('end', function() {
            console.log('DEBUG - httpRequest - res.on end');
            try {
                console.log('DEBUG - httpRequest - body = ' + body);
                body = JSON.parse(Buffer.concat(body).toString());
            } catch(e) {
                console.log('DEBUG - httpRequest -  reject(e)');
                reject(e);
            }
            resolve(body);
        });
    });
    // reject on request error
    req.on('error', function(err) {
        // This is not a "Second reject", just a different sort of failure
        console.log('DEBUG - httpRequest - req.on error (second) err = ' + err.response);
        reject(err); // *** <--- Why doesn't the error message here get returned to the calling function?
    });
    if (postData) {
        req.write(postData);
    } 
    req.end();
    console.log('DEBUG - httpRequest - req.end');
});

}



via Kevin Key

No comments:

Post a Comment