我有一个无服务器的lambda函数写在Node.JS中。什么是在无服务器lambda中返回HTTP错误代码的正确方法
返回错误代码的最佳/正确方法是什么?
,我现在使用权的模式(!和它的作品)是:
module.exports.endpoint = (event, context, callback) => {
const response = {
statusCode: 404,
body: JSON.stringify({ message: 'Hello World!' })
};
callback(null, response);
}
当我拨打电话,例如从邮递员,我的终点,我得到:
Status: 404 Not Found
其中正是我所期待的。
此外,在日志中我可以看到:
Serverless: GET/(λ: get)
Serverless: [404] {"statusCode":404,"body":"{\"message\":\"Hello World!\"}"}
行之有效。
让我困扰的是我通过null
作为错误。放眼其他几个教程/例子,我发现模式,如:
https://aws.amazon.com/blogs/compute/error-handling-patterns-in-amazon-api-gateway-and-aws-lambda/
https://serverless.com/framework/docs/providers/aws/events/apigateway/
callback ("the sky is falling!");
callback("[BadRequest] Validation error: Missing field 'name'");
callback("[404] Not Found");
callback(new Error('[404] Not found'));
callback(JSON.stringify(myErrorObj));
他们都非常清楚了,你可以指定HTTP状态代码 - 但什么,我得到的是到底HTTP状态代码200。当我看我的日志可以看出,错误与200后直如下:
Serverless: GET/(λ: get)
Serverless: Failure: the sky is falling!
Serverless: Replying 200
Serverless: GET/(λ: get)
Serverless: Failure: [BadRequest] Validation error: Missing field 'name'
Serverless: Replying 200
Serverless: GET/(λ: get)
Serverless: Failure: [404] Not Found
Serverless: Replying 200
Serverless: GET/(λ: get)
Serverless: Failure: [404] Not found
Serverless: Replying 200
Serverless: GET/(λ: get)
Serverless: Failure: {"errorType":"InternalServerError","httpStatus":500,"message":"An unknown error has occurred. Please try again."}
Serverless: Replying 200
在这个地方,我发现如下解释: https://github.com/serverless/serverless/issues/4119
如果要回应HTTP错误在这种情况下,你必须 编码HTTP错误是成功的拉姆达响应
与下面的例子:
Sample 403:
callback(null, { statusCode: 403, body: "Forbidden", headers: { "Content-Type": "text/plain" } });
Sample 404:
callback(null, { statusCode: 400 });
所以这与我的基本相同。为了完整起见,我可以补充说,还有很多使用context.fail(result)
或context.succeed(result)
的示例 - 但从我收集的context
已弃用,不应使用(即使它仍然有效)。
什么是使用callback(error)
?
我看到你在最后使用相同的方法:'return callback(null,createResponse)' - 将'null'作为错误传递,然后产生实际的错误。 – iaforek
是的。正如我所说的,您应该为API Gateway Lambdas处理错误。 – dashmug
@iaforek你还有什么困惑? – dashmug