我正在使用 play 框架 (2.3.x) 来构建一个宁静的 API。
今天,我在 API 控制器中的所有 api 函数周围有一个 try/catch 块,以便能够捕获异常并返回通用的“错误 json”对象。
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"))
}
}
我的问题是:是否有必要在每个 api 函数中都有一个 try/catch 东西,或者是否有更好/更通用的方法来解决这个问题?
@Mikesname 链接是解决您问题的最佳选择,另一种解决方案是使用动作组合 https://www.playframework.com/documentation/2.0/ScalaActionsComposition并创建您的操作(如果您想对操作有更高的控制权):
def APIAction(f: Request[AnyContent] => Result): Action[AnyContent] = {
Action { request =>
try { f(request) }
catch { case _ => InternalServerError(...) }
}
}
def index = APIAction { request =>
...
}
或者使用更惯用的 ScalaTry
:
def APIAction(f: Request[AnyContent] => Result): Action[AnyContent] = {
Action { request =>
Try(f(request))
.getOrElse(
InternalServerError(Json.obj("code" -> "500", "message" -> "Server error"))
)
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)