有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java AWS API网关集成响应

我正在使用AWS Lambda和API Gateway,API的响应代码出现问题,
如果出现异常,我会在响应中将responseCode设置为400,
但API状态是200

我发现我的解决方案与AWS API网关的集成响应有关,
我创建了应用程序需要的所有可能的Http状态代码,
我在集成响应中设置了Lambda Error Regex,
但尽管我在API响应中发送了“responseCode”:“400”(响应类型在Java中是JsonObject),但我仍然获得了200的API状态

我有以下代码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?


共 (1) 个答案

  1. # 1 楼答案

    Lambda Error Regex不是正则表达式。把它改成.*"responseCode":\s"400".*就可以了

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