gpt4 book ai didi

scala - play框架中的错误处理

转载 作者:行者123 更新时间:2023-12-04 17:09:30 24 4
gpt4 key购买 nike

我正在使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com