LoginSignup
39
33

More than 5 years have passed since last update.

[AWS]API Gateway + Lambda(Java)で適切なHTTPステータスを返す

Last updated at Posted at 2016-02-06

やりたいこと

  • API Gateway + Lambdaの構成で、200以外のHTTPステータスコードを返却する。

LambdaってHTTPステータス返せないし、どうするんだろうってことでやってみました。

うまくいったやり方

以下の2つを定義すればOKです。

  • Method Response」で返したいHTTPステータスコードを定義する。[^1]
  • Integration Response」でHTTPステータスコードを返す条件を定義する。

実際の手順

  • Method Execution」の「Method Response」で「Add Response」をクリック。
  • HTTP status code」の項目にステータスコードをセットし、右のチェックボタンをクリック。
    スクリーンショット 2016-02-06 20.20.11.png

  • Integration Response」の「Add integration response」を開く。

  • Lambda Error Regex」にこのステータスコードを返却する条件となる正規表現を入力。

Lambda Error Regex」の項目はLambdaからthrowされたExceptionのmessageの内容を参照しています。
なのでLambdaからExceptionをthrowするときにmessageに何か目印を埋め込む必要があります。
僕の場合はExceptionのwrapperを作成して、messageの先頭にステータスコードを入れるようにしました。

こんな感じでmessageの先頭にステータスコードをくっつけています。

ApiGatewayException.java
private HttpStatusCode httpStatusCode;

public ApiGatewayException(Throwable t, HttpStatusCode httpStatusCode, String message) {
        super(t);
        this.message = message;
        this.httpStatusCode = httpStatusCode;
    }

@Override
public String getMessage() {
    return httpStatusCode.getCode() + ": " + this.message;
}
  • Method response status」で実際に返すステータスコードを選択。
    スクリーンショット 2016-02-06 20.22.11.png

  • save」をクリック

これでstageにデプロイしてAPIを叩くと設定したステータスコードが返ってきます。

ちなみにエラーは以下の形で帰ってくるので、Modelを作成し、「Integration Response」の「Mapping Templates」でマッピングすれば任意のフォーマットで返すことも可能です。

error.json
{
    "errorMessage":"[メッセージ]",
    "errorType":"[Exceptionの型]",
    "stackTrace":[StackTrace文字列の配列]
}
39
33
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
39
33