AWS API网关集成响应

问题描述 投票:0回答:1

我正在使用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”。

我的预期输出是“responseCode”:“400”但是,API的状态也应该变为400而不是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网关方法响应 - enter image description here

AWS API网关集成响应 - enter image description here

邮递员回应 - API状态显示200 Ok,而我希望它为400. enter image description here

我指的是以下链接 - 1. https://forums.aws.amazon.com/thread.jspa?threadID=192918 2. Is there a way to change the http status codes returned by Amazon API Gateway?

java amazon-web-services aws-lambda aws-api-gateway
1个回答
3
投票

您的Lambda Error Regex不是正则表达式。将它改为.*"responseCode":\s"400".*应该这样做。

但对于那个用例,激活Lambda proxy integration会更好。这提供了一种更灵活的方式来直接从lambda函数设置响应代码。

© www.soinside.com 2019 - 2024. All rights reserved.