ulejon
ulejon

Reputation: 641

Handling exceptions in Play framework

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?

Upvotes: 5

Views: 1761

Answers (2)

Ende Neu
Ende Neu

Reputation: 15783

@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"))
      )
  }
}

Upvotes: 5

cchantep
cchantep

Reputation: 9168

You could wrap any unsafe result in a future, having thus a Future[Result], turning action into async.

def myAction = Action async Future(Ok(funcRaisingException))

Upvotes: -3

Related Questions