Advertisement
mitrakov

Play: Handling timeouts

Feb 24th, 2019
374
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 0.72 KB | None | 0 0
  1. import javax.inject._
  2. import scala.concurrent.duration._
  3. import scala.concurrent.{ExecutionContext, Future, TimeoutException}
  4. import scala.language.postfixOps
  5. import play.api.mvc._
  6. import play.api.libs.concurrent.Futures
  7. import play.api.libs.concurrent.Futures._
  8.  
  9.  
  10. @Singleton
  11. class MyController @Inject()(cc: ControllerComponents)(implicit ec: ExecutionContext, f: Futures) extends AbstractController(cc) {
  12.  
  13.   def longComputation: Future[Int] = Future{
  14.     Thread.sleep(2000)
  15.     1
  16.   }
  17.  
  18.   def hey: Action[AnyContent] = Action.async {
  19.     longComputation.withTimeout(5 seconds).map { i =>
  20.       Ok("Got result: " + i)
  21.     }.recover {
  22.       case e: TimeoutException => InternalServerError(s"timeout: $e")
  23.     }
  24.   }
  25. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement