概要
GAEで使用できるCloud Endpoints Frameworkは、デフォルトだとなぜか500系をすべて503で返すような仕様になっており、500と503を分けたいときなどに迷惑な動きをします。
コードを読んだ結果、この挙動を変更出来そうだったので備忘録として残しておく。
サーブレットの設定を追加する
結論から言うとweb.xml
にenableExceptionCompatibility
というパラメータを設定すると、設定したステータスコードでレスポンスを返す事ができるようになる。
<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);