1
1

More than 3 years have passed since last update.

Cloud Endpoints Frameworkで任意のステータスコードを返す

Last updated at Posted at 2020-03-06

概要

GAEで使用できるCloud Endpoints Frameworkは、デフォルトだとなぜか500系をすべて503で返すような仕様になっており、500と503を分けたいときなどに迷惑な動きをします。
コードを読んだ結果、この挙動を変更出来そうだったので備忘録として残しておく。

サーブレットの設定を追加する

結論から言うとweb.xmlenableExceptionCompatibilityというパラメータを設定すると、設定したステータスコードでレスポンスを返す事ができるようになる。

<servlet>
    <servlet-name>EndpointsServlet</servlet-name>
    <servlet-class>com.google.api.server.spi.EndpointsServlet</servlet-class>
    <!-- ここにパラメータを追加 -->
    <init-param>
        <param-name>enableExceptionCompatibility</param-name>
        <param-value>false</param-value>
    </init-param>
</servlet>

実装

例外が投げられたとき、com.google.api.server.spi.response.ErrorMap#getHttpStatusにステータスコードが渡されて、500系を503に変更するような処理が走ります。
このメソッドの先頭でチェックしている enableExceptionCompatibility という変数がサーブレットの設定を読み込んで設定されるため、上記の設定をすることで指定どおりのステータスコードをレスポンスに設定するようになります。

com.google.api.server.spi.response.ErrorMap.java
public int getHttpStatus(int lilyStatus) {
  if (!enableExceptionCompatibility) {
    return lilyStatus;
  }
  if (lilyStatus >= 500) {
    return 503;
  }
  Error error = errors.get(lilyStatus);
  if (error == null) {
    return 404;
  }
  return error.httpStatus;
}

2020/03/12追記

Guiceを使う場合

Guiceを使う場合はEndpointsModuleを継承したクラスの中で以下のように初期パラメータを設定する。

ServletInitializationParameters initParameters = ServletInitializationParameters.builder()
        .addServiceClasses(ImmutableList.of(
                HogeHogeApi.class
        ))
        .setExceptionCompatibilityEnabled(false)
        .build();

configureEndpoints("/_ah/api/*", initParameters);
1
1
2

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
1
1