【发布时间】: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 客户端问题。你正在使用什么库?喜欢
fetch、axios... -
嘿!我只在后端使用 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