我是新玩的框架。我将 Play Framework (2.4)
与 scala
一起使用。我需要您对异常处理的意见。
我们的Play客户端控制器正在调用播放服务器控制器。现在我们需要引入将从服务器抛出的自定义异常,客户端将捕获该异常并执行必要的操作。
现在,当我从服务器抛出任何异常时,它并没有按原样到达客户端。我在此背后发现的原因是,Play捕获所有异常并将其转换为500 Internal Server Error
那么可以在不修改的情况下向客户端发送自定义异常吗?
答案 0 :(得分:2)
通过在播放控制器中自行处理异常来停止播放500
您可以为此目的编写自定义操作构建器
object ExceptionCatchingAction extends ActionBuilder[Request] {
override def invokeBlock[A](request: Request[A], block: (Request[A]) => Future[Result]): Future[Result] = {
block(request).recover { case th =>
//use meaningful http codes instead of OK here based on the exception type
Ok(Json.obj("msg" -> "error occurred", "info" -> "error info"))
}
}
}
像这样使用
object ExampleController extends Controller {
def doStuff = ExceptionCatchingAction { req =>
throw new Exception("foo")
}
}
您的客户将无法获得所有例外情况。因此,客户现在可以决定做什么。