我正在编写一个内部使用的应用程序接口,这是我第一次使用serverless framework。我正在用Node.js编写一个Lambda函数,并使用AWS API Gateway连接到它。
在某些情况下,我想返回一个自定义的错误消息,并且我正在尝试编写一个允许我这样做的函数。现在,每当Lambda进程失败时,我都会收到来自API的标准消息。在代码中,如果我尝试使用process.exit(1)
终止进程,即使我已经使用callback()
返回了一个错误,也会得到一个一般性错误
{
"message": "Internal server error"
}
如果我不使用process.exit(1)
,我会在日志中看到通过callback()
返回的错误,但该过程会继续,最终会超时:
{
"message": "Endpoint request timed out"
}
我尝试过使用callback()
方法返回错误的几种不同方法,但到目前为止还没有成功。我尝试过这种方法:
async function return_error(callback, context, error, returnCode){
console.error("FATAL ERROR: ", error);
let ErrorObj = {
errorType : "InternalServerError",
httpStatus : 500,
requestId : context.awsRequestId,
errorMessage : error
}
callback(JSON.stringify(ErrorObj));
process.exit(1);
}
还有这一条:
async function return_error(callback, error, returnCode){
console.error("FATAL ERROR: ", error);
callback({
isBase64Encoded: false,
statusCode: returnCode,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({"Error Message:": error})
}, null);
process.exit(1);
}
(很抱歉,两者之间的语法稍有不同。)
到目前为止,我还不能通过API向用户返回任何错误。我的错误总是被记录下来,并且函数继续执行。任何帮助都将不胜感激。谢谢!
作为参考,我的serverless.yml文件的相关部分:
service: #Name of service
provider:
name: aws
runtime: nodejs8.10
role: #ARN of Iam role
functions:
screenshot:
handler: #Name of handler
timeout: 30
memorySize: 1280
reservedConcurrency: 10
events:
- http:
method: get
path: #path
contentHandling: CONVERT_TO_BINARY
authorizer:
type: aws_iam
plugins:
- serverless-plugin-chrome
- serverless-apigw-binary
- serverless-apigwy-binary
package:
exclude:
- node_modules/puppeteer/.local-chromium/**
custom:
apigwBinary:
types:
- '*/*'
发布于 2019-04-11 23:21:05
Node.js的亚马逊网络服务错误回调并不像广告中所说的那样工作。根据docs的说法,所有人需要做的就是确保自定义错误扩展错误原型。然而,经过10多个小时的测试,我发现这完全不是真的。
返回错误回调的唯一方法是回调错误,就好像它是成功的一样(例如,如果你从{"message": "Internal server error"}
网关触发了Lambda函数)。
TL;DR:callback(errorResponse, null)
不起作用,但callback(null, errorResponse)
起作用。
发布于 2018-11-17 15:01:04
为了让APIgateway检测到您的响应,您的lambda函数需要返回成功。试试这个:
async function return_error(callback, error, returnCode){
console.error("FATAL ERROR: ", error);
callback(null, {
isBase64Encoded: false,
statusCode: returnCode,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({"Error Message:": error})
});
}
https://stackoverflow.com/questions/53345168
复制相似问题