【问题标题】:Want to get an AWS lambda error to client console想要将 AWS lambda 错误发送到客户端控制台
【发布时间】:2020-06-30 13:14:39
【问题描述】:

我正在尝试让 Lambda 传递的错误消息显示在我的客户端上。基本上我从我的客户端调用一个 API Gateway 端点,它执行一个 lambda。这个函数有一个特定的条件,如果这个条件失败,我想向我的客户发送一条特定的消息。这是我目前拥有的。

图书馆:

export function failure(body) {
    return buildResponse(500, body);
}

function buildResponse(statusCode, body) {
    return {
        statusCode: statusCode,
        headers: {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Credentials': true
        },
        body: body
    };
}

和实际功能:

export async function main(event, context) {

    const data = JSON.parse(event.body);

    const saleCount = await getSaleCount();

    if (count >= 25) {
        // This is the error i'm referring to
        return failure({ status: false, error: 'My error' });
    }

    const params = {
        TableName: process.env.salesTable,
        Item: {
            foo: bar
        }
    };

    try {
        await dynamoDbLib.call('put', params);
        return success(params.Item);
    } catch(e) {
        console.log(e);
        return failure({ status: false });
    }
}

async function getSaleCount(foo) {
    // do stuff and return value
    return bar;
}

我似乎无法在前端收到此错误中的消息。有一个try-catch子句,错误肯定是被catch发现的,但错误只是显示为

Error: Request failed with status code 500
    at createError (createError.js:16)
    at settle (settle.js:17)
    at XMLHttpRequest.handleLoad (xhr.js:59)

此外,我实际上可以在“网络”选项卡上看到该消息作为响应:

{"status": "false", "error": "My error"}

这是一个 Lambda 代理集成,所以我尝试按照此页面上的方法进行操作: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html 含义:

// This returns me a 502 on the frontend
throw new Error('My error');

// This also doesn't allow me to access the message
return {statusCode: 400, body: 'My error'};

我现在完全不知所措,所以我非常感谢任何意见。非常感谢!

【问题讨论】:

  • 这是您的 http 客户端问题。你正在使用什么库?喜欢fetchaxios...
  • 嘿!我只在后端使用 aws-sdk,在前端使用 aws-amplify。呼叫以非常简单的方式进行。 `从'aws-amplify'导入{API}; function loadPurchases(user) { return API.get('some name', path); } `
  • 在您的catch 块中,尝试行console.log(e.response.data); - e 是错误对象
  • 抱歉回复晚了,但你绝对是英雄。 e.response.data.error 让我得到了我正在寻找的实际错误消息。非常感谢!

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


【解决方案1】:

在我的情况下,e.response.data 为空,因为我得到的响应不是 json 而是文本。但在我的网络响应中,我可以看到该消息。

我的解决方案是在请求对象中添加一个responseType = "text"。之后我可以在 data 属性中看到一些文本。

responseType 的允许值为“arraybuffer”、“blob”、“document”、“json”或“text”;如果未指定,则默认为“json”。

您可以在此处阅读更多内容:https://docs.amplify.aws/lib/restapi/fetch/q/platform/js#accessing-query-parameters--body-in-lambda-proxy-function

【讨论】:

    猜你喜欢
    • 2011-02-05
    • 2020-10-20
    • 2021-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-14
    • 2020-04-08
    相关资源
    最近更新 更多