我正在使用AWS Lambda和API Gateway,并面临我的API响应代码的问题,
如果出现异常,我在响应中将responseCode设置为400,
但API状态为200 .
我发现我的解决方案与AWS API Gateway的集成响应有关,
我创建了我的应用程序所需的所有可能的Http状态代码,
我在集成响应中设置了Lambda Error Regex,
但是我的API状态仍为200,尽管我在我的API响应中发送"responseCode":"400"(响应类型是Java中的JsonObject) .
我有以下代码AWS Lambda代码,
我将ErrorCode作为查询参数传递给我的Get方法,
并返回相同的错误代码作为响应,例如 . "responseCode":"400" .
My expected output is "responseCode" : "400" but, the API's status should also become 400 instead of 200.
public class MainHandler implements RequestHandler<JSONObject, JSONObject> {
public JSONObject handleRequest(JSONObject request, Context context) {
try {
JSONObject requestJson = (JSONObject) new JSONParser().parse(request.toString());
System.out.println("RequestJson : " + requestJson);
JSONObject params = (JSONObject) requestJson.get("params");
System.out.println("Params : " + params);
JSONObject queryString = (JSONObject) params.get("querystring");
System.out.println("QueryString : " + queryString);
String error = (String) queryString.get("errorCode");
System.out.println("ErrorCode : " + error);
JSONObject resp = new JSONObject();
resp.put("responseCode", error);
return resp;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
AWS API Gateway Method Response -
AWS API Gateway Integration Response -
Postman response -
API状态显示200 Ok,而我希望它为400.
I am referring the following links -
1 回答
您的Lambda Error Regex不是正则表达式 . 将其更改为
.*"responseCode":\s"400".*
应该这样做 .但对于该用例,最好激活Lambda proxy integration . 这提供了一种更灵活的方法来直接从lambda函数设置响应代码 .