我通过以下命令创建了无服务器框架的功能:
sls function create some/api
然后创建了schelton代码:
'use strict';
module.exports.handler = function(event, context, cb) {
return cb({
message: 'Go Serverless! Your Lambda function executed successfully!'
});
};
,响应模板如下所示:
S-function.json
"responses": {
"400": {
"statusCode": "400"
},
"default": {
"statusCode": "200",
"responseParameters": {},
"responseModels": {
"application/json;charset=UTF-8": "Empty"
},
"responseTemplates": {
"application/json;charset=UTF-8": ""
}
}
}
但是,当我将错误对象返回到cb(err, null)
之类的回调函数时,错误消息已正确显示,但statusCode为200。
如果我更改为调用cb("400", err)
之类的回调函数,则statusCode正确返回400,但响应正文不好:{"errorMessage":"400"}
。
是否有任何好的设置来显示bot statusCode(不仅400,还有401,403,404,500 ......等等)和错误消息?
答案 0 :(得分:1)
我使用以下响应模板。如果从lambda函数返回的消息与响应模板中指定的selectionPattern
匹配,则它将返回正确的状态代码。
"responseTemplate": {
"400": {
"selectionPattern": "^\\[BadRequest\\].*",
"statusCode": "400"
},
"401": {
"selectionPattern": "^\\[Unauthorized\\].*",
"statusCode": "401"
},
"403": {
"selectionPattern": "^\\[Forbidden\\].*",
"statusCode": "403"
},
"404": {
"selectionPattern": "^\\[NotFound\\].*",
"statusCode": "404"
},
"409": {
"selectionPattern": "^\\[Conflict\\].*",
"statusCode": "409"
},
"500": {
"selectionPattern": "^\\[Process exited|ServerError\\].*",
"statusCode": "500"
},
"504": {
"selectionPattern": "^\\[Task timed out\\].*",
"statusCode": "504"
},
"default": {
"statusCode": "200",
"responseParameters": {},
"responseModels": {},
"responseTemplates": {
"application/json": ""
}
}
}