通过AWS API从Lambda获取错误字符串

时间:2019-02-17 18:37:30

标签: javascript node.js amazon-web-services aws-lambda

考虑以下Lambda函数示例:

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

Lambda会这样输出此错误:

{
  "errorMessage": "Account not found"
}

这正是我想要的。但是,请考虑然后通过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);
    });
});

在这种情况下,我发现错误总是转换为[object Object]字符串。 Lambda似乎是从回调中获取错误对象(它创建的错误对象),然后将其包装在另一个错误对象中。因此最终Lambda.invoke会这样做:

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

但它不返回此构建对象,而是返回,

{
    errorMessage: '[object Object]'
}

有人看到解决方法吗?我不想更改Lambda函数输出错误的方式。我只想从Lambda调用函数中获取正确的错误。由于Lambda.invoke()如何再次包装错误,这完全不可能吗?

0 个答案:

没有答案