Sunday 19 March 2017

Node Promise and AWS Lambda error handling

I am doing some error handling in my node Lambda, using native promises. For some reason, my promise.reject never triggers. I am specifically sending in a bad url to get it to fail, yet AWS sends back 502 "Bad Gateway". This is presumably the way AWS handles internal server issues, which is fine, but I want to send back the reject reason. What am I doing wrong?

Promise

function parseData(data) {
    url = 'https://notarealurl';

    return new Promise((resolve, reject) => {
        https.get(url, (res) => {
            let body = '';
            res.on('data', (chunk) => {
                body += chunk;
            })
            .on('end', () => {
                resolve(body);
            })
            //this reject will trigger when there is an error with the request
            .on('error', (err) => {
                const rejectReason = {
                    statusCode: 500,
                    body: 'Internal Server Error: ' + err
                };
                reject(rejectReason)
            });
        })
    });
}

my handler:

function handler(event, context) {
    parseData(event.queryStringParameters)
    .then((result) => {
        const parsed = JSON.parse(result);
        //handle error message returned in response
        if (parsed.error) {
            const oAuthError = 'Authentication Error';
            let error = {
                headers: {"Content-Type": "application/json"},
                body: JSON.stringify(parsed.error)
            };
            if(parsed.error.type === oAuthError) {
                error.statusCode = 401;
                context.succeed(error);
            } else {
                error.statusCode = 404;
                return context.succeed(error);
            }
        } else {
            return context.succeed({
                statusCode: 302,
                headers: "Success"
              });
        }
    })
    .catch((reason) => {
        console.log('Promise rejected!!!!', reason)
    })
}

What is the AWS error coming out instead of my promise.reject errorReason?



via jmcgui05

No comments:

Post a Comment