在Play框架中处理异常 [英] Handling exceptions in Play framework

查看:103
本文介绍了在Play框架中处理异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用播放框架(2.3.x)构建一个宁静的API.

I'm using play framework (2.3.x) for building a restful API.

今天,我在API控制器中的所有api函数周围都有一个try/catch块,以便能够捕获异常并返回通用的错误json"对象.

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.

示例:

def someApiFuntion() = Action { implicit request =>
    try {
        // Do some magic
        Ok(magicResult)
    } catch {
        case e: Exception =>
            InternalServerError(Json.obj("code" -> INTERNAL_ERROR, "message" -> "Server error"))
    }
}

我的问题是:是否有必要在每个api函数中进行try/catch事情,或者有解决此问题的更好/更通用的方法?

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链接是解决您问题的最佳选择,另一种解决方案是使用

@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 =>
  ...
}

或者使用更惯用的Scala Try:

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

这篇关于在Play框架中处理异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆