5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Play Framework (Java) の WS を使った時のタイムアウト

Posted at

Play Framework では、Play WS API なるものを使うと、Web サービスへのアクセスが簡単にできます。

ドキュメントの中の「Configuring the HTTP client」を見ると、ws.timeout なるパラメータを設定することで、タイムアウトを設定出来ます。単位はミリ秒で、デフォルトは 120000、つまり2分です。外部サービスが重い時に自分のサービスまで重くなってしまうのは避けたいので、この値は基本小さくして、必要に応じてアクセス時に上げるのがいいと思います。

さて、タイムアウトした時の挙動ですが、特にドキュメントにありません。では何が起こるのかというと Promise<Response>#getjava.util.concurrent.TimeoutException が発生します。

えー!throws には RuntimeException しか書いてないじゃないかー!と言いたい気持ちは分かるのですが、チェック例外である TimeoutException が発生します。多分、中で Scala と Java を行ったり来たりしてるうちに、チェック例外であるということが隠されてしまったのでしょう。

非チェック例外しか投げないはずのメソッドに対して

String url = "http://example.com/image.jpg";
try {
  response = WS.url(url).get().get();
} catch (TimeoutException e) {
  Logger.warn("Timeout: " + url);
}

みたいなコードを書いても「Unreachable catch block for TimeoutException. This exception is never thrown from the try statement body」などと怒られてしまいます。もしタイムアウトであるかどうかを確認したければ、Exception を catch して、instanceof などするしかないようです。

5
5
1

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?