Skip to content

Instantly share code, notes, and snippets.

@inmyth
Last active February 13, 2019 15:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save inmyth/3df58e683efb0b66e9123a536a5cb171 to your computer and use it in GitHub Desktop.
Save inmyth/3df58e683efb0b66e9123a536a5cb171 to your computer and use it in GitHub Desktop.
Vertx, Scala Future example
val vertx = Vertx.vertx()
vertx.createHttpServer().requestHandler(req => {
req.path() match {
case p if p contains("/user") =>
val f = for {
f1 <- Future { req.getParam("id").get.toInt }
f2 <- if (f1 < 100) Future.unit else Future.failed(CustomException())
f3 <- Future { getUserFromDb(f1) }
} yield f3
f map (r => printout(req, r)) recover {case exception => printout(req, handleException(exception))}
case _ => printout(req, "Default page")
}
})
.listen(8080)
def printout(req: HttpServerRequest, msg: String) = req.response().end(msg)
def handleException(e: Throwable): String = {
e match {
case t: NoSuchElementException => "Missing parameter"
case t: NumberFormatException => "Parameter not number"
case t: CustomException => "Custom exception"
case t: SQLException => "Database error"
case _ => "Unknown error"
}
}
def getUserFromDb(id: Int) = "mock user name"
case class CustomException() extends Exception("custom exception")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment