首页 > 解决方案 > Getting error string from Lambda invoked via AWS API

问题描述

Consider the following example Lambda function:

//get-account
exports.handler = (data, context, callback) => {
    callback("Account not found");
};

Lambda would output this error like so:

{
  "errorMessage": "Account not found"
}

This is exactly what I want. However, consider then calling this function via the AWS API

return new Promise((resolve, reject) => {
    Lambda.invoke({
        FunctionName: 'get-account',
        InvocationType: "RequestResponse",
        Payload: JSON.stringify({ account_id: account_id })
    }, function(err, data) {

        //only true if the invocation failed...
        if(err) { return reject(err); }

        //parse the payload. We will need it regardless of error/success
        let response = JSON.parse(data.Payload);

        //did the function throw an error?
        if(data.FunctionError) {
            //the error message will be [object Object], which is no good!
            reject(response.errorMessage);
            return;
        }

        //success!
        resolve(response);
    });
});

In this case, I find the error is always converted to the [object Object] string. Lambda appears to take the error object from the callback (the error object it creates) and then wraps it in another error object. So ultimately Lambda.invoke is doing this:

{
    errorMessage: {
        errorMessage: "Account not found"
    }
}

But instead of returning this built object, it returns,

{
    errorMessage: '[object Object]'
}

Anyone see a way around this? I do NOT want to change how my Lambda function outputs errors. I only want to get the correct error from the Lambda invoke function. Is this simply not possible due to how Lambda.invoke() wraps the error again?

标签: javascriptnode.jsamazon-web-servicesaws-lambda

解决方案


推荐阅读