LoginSignup
0

More than 5 years have passed since last update.

このFutureを使ったコードは出来損ないだ、正しく実行されないよ

Posted at

みたいなことをいうときに使うサンプルコード:

NGなコード
import com.twitter.finagle.Failure
import com.twitter.util.{Await, Future}

object Example {
  def ng: Future[Int] = {
    val x = 1 / 0
    Future.value(x)
  }

  def main(args: Array[String]): Unit = {
    val x = ng handle {
      case _: Throwable => Failure.rejected("invalid value")
    }
    println(Await.result(x))
  }
}

=>

標準エラー
Exception in thread "main" java.lang.ArithmeticException: / by zero
    at Example$.ng(Example.scala:5)
    at Example$.main(Example.scala:8)
    at Example.main(Example.scala)

Exceptionがhandleされない。401 Authorization Requiredなどの4xx系のエラーを返そうとしたときに5xx系のエラーが返ってしまう。

OKなコード
import com.twitter.finagle.Failure
import com.twitter.util.{Await, Future}

object Example {
  def ok: Future[Int] = Future {
    1 / 0
  }

  def main(args: Array[String]): Unit = {
    val x = ok handle {
      case _: Throwable => Failure.rejected("invalid value")
    }
    println(Await.result(x))
  }
}

=>

標準出力
Failure(invalid value, flags=0x09) with NoSources

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
0