I'm using play framework (2.3.x) for building a restful API.
Today I have a try/catch block surrounding all my api functions in the API controller, to be able to catch the exceptions and return a generic "error json" object.
Example:
def someApiFuntion() = Action { implicit request =>
    try {
        // Do some magic
        Ok(magicResult)
    } catch {
        case e: Exception =>
            InternalServerError(Json.obj("code" -> INTERNAL_ERROR, "message" -> "Server error"))
    }
}
My question is: is it necessary to have a try/catch thingy in each api function, or is there a better/more generic way of solving this?
@Mikesname link is the best option for your problem, another solution would be to use action composition and create your action (in case you want to have a higher control on your action):
def APIAction(f: Request[AnyContent] => Result): Action[AnyContent] = {
  Action { request =>
    try { f(request) } 
    catch { case _ => InternalServerError(...) }
  }
}
def index = APIAction { request =>
  ...
}
Or using the more idiomatic Scala Try:
def APIAction(f: Request[AnyContent] => Result): Action[AnyContent] = {
  Action { request =>
    Try(f(request))
      .getOrElse(
        InternalServerError(Json.obj("code" -> "500", "message" -> "Server error"))
      )
  }
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With