我正在使用 Play Framework 开发 REST API。我想为我的所有操作实现集中的错误处理。
实现这一目标的最佳方法是什么?
最佳答案
另一种方法是使用 filter ,例如:
object ExceptionFilter extends EssentialFilter {
def apply(nextFilter: EssentialAction) = new EssentialAction {
def apply(requestHeader: RequestHeader) = {
val next: Iteratee[Array[Byte], Result] = nextFilter(requestHeader)
// Say your backend throws an ItemNotFound exception.
next recoverWith {
case e: ItemNotFound => Iteratee.ignore[Array[Byte]]
.map(_ => Results.NotFound("Item not in the database!"))
}
}
}
}
然后将其连接到您的全局设置中:
object Global extends WithFilters(CSRFFilter(), ExceptionFilter) with GlobalSettings
如果需要,这可能允许您对请求正文执行某些操作。我同意在大多数情况下使用
GlobalSettings.onError
可能是最简单的方法。
关于scala - play框架中的错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25547795/