Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 327
ulejon Avatar asked Nov 01 '22 18:11

ulejon


1 Answers

@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"))
      )
  }
}
like image 183
Ende Neu Avatar answered Nov 15 '22 05:11

Ende Neu