Last active
February 13, 2019 15:12
-
-
Save inmyth/3df58e683efb0b66e9123a536a5cb171 to your computer and use it in GitHub Desktop.
Vertx, Scala Future example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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