Handling exceptions in Play framework

风格不统一 提交于 2020-01-01 06:16:05

问题


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?


回答1:


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



回答2:


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))


来源:https://stackoverflow.com/questions/25574643/handling-exceptions-in-play-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!