首页 文章

AWS API网关集成响应

提问于
浏览
0

我正在使用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 -
enter image description here

AWS API Gateway Integration Response -
enter image description here

Postman response -
API状态显示200 Ok,而我希望它为400.
enter image description here

I am referring the following links -

  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 回答

  • 3

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

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

相关问题