playframework - Play Framework:如果在 JSON 解析期间抛出异常,则返回 400 的 BodyParser
问题描述
如果在 JSON 解析期间抛出异常,则默认 jsonBodyParser
返回 500 - 例如,如果存在 arequire(…)
并且不满足某些条件。我想让这个场景返回 400。如何扩展默认 JSONBodyParser
来实现这个目标?
解决方案
BodyParser
您可以在解析请求正文时定义一个处理(特定?)异常的自定义:
val exceptionalJsonParser = BodyParser { h =>
try {
parse.tolerantJson(h) // <- call your normal parser here
} catch {
// catching all non-fatal exceptions here might not be a good idea,
// be more specific !
case NonFatal(e) => Accumulator.done(Left(BadRequest(e.getMessage)))
}
}
def action = Action.async(exceptionalJsonParser) {
...
}
推荐阅读
- reactjs - 如何在不使用'exact'参数的情况下在反应路由器dom中构建路由?
- apache-nifi - Nifi > RunMongoAggregation > 抛出超时异常
- routes - 等效于 Adonis JS 的 Ziggy
- javascript - flutter_webview 在一个 javascript 通道中声明多个 javascript 接口
- css - 在 Material ui 样式中编写 JS
- rest-assured - AllureRestAssured ,如何忽略日志记录头
- java - Maven:解析工件时出错 - 提供节点名或服务名,或未知
- c++ - 设计游戏循环
- r - 无法打开 R Markdown:需要以下软件包的更新版本
- react-native - 当应用程序在后台或在本机反应中处于终止状态时跟踪位置