Handling exceptions in the replay structure

I am using the play framework (2.3.x) to build a laid-back API.

Today I have a try / catch block surrounding all my api functions in an API controller to catch 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, do I need to have a try / catch thingy in every api function, or is there a better / more general way of solving this?

+3


source to share


2 answers


The @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 more control over your action):

def APIAction(f: Request[AnyContent] => Result): Action[AnyContent] = {
  Action { request =>
    try { f(request) } 
    catch { case _ => InternalServerError(...) }
  }
}

def index = APIAction { request =>
  ...
}

      



Or using 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"))
      )
  }
}

      

+4


source


You can carry over any unsafe result in the future, while still Future[Result]

making the action async.



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

      

-2


source







All Articles