首页 > 解决方案 > Play Framework:如果在 JSON 解析期间抛出异常,则返回 400 的 BodyParser

问题描述

如果在 JSON 解析期间抛出异常,则默认 jsonBodyParser返回 500 - 例如,如果存在 arequire(…)并且不满足某些条件。我想让这个场景返回 400。如何扩展默认 JSONBodyParser来实现这个目标?

标签: playframework

解决方案


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) { 
  ... 
}

推荐阅读