将JsError转换为人类可读的错误数组?

时间:2018-01-19 16:24:05

标签: scala playframework playframework-2.6

我试图让Play验证+将json请求体转换为case类。如果验证失败,我想发送一份人类可读的错误消息列表。

我的案例类是一个简单的登录请求:

case class LoginReq(user: String, password: String)

我想以简单的格式发送错误,例如:

{"errors": ["User was not provided", "Password was not provided"]}

这是我迄今为止实施的内容:

@Singleton
class LoginController @Inject()(cc: ControllerComponents) extends AbstractController(cc) {

    case class LoginReq(user: String, password: String)
    implicit val reqFormat = Json.format[LoginReq]


  def index() = Action(parse.json) { req =>

          val loginReq = req.body.validate[LoginReq]
          loginReq match {
              case JsSuccess(r: LoginReq, path: JsPath) => Ok(Json.toJson(r))
              case e: JsError =>
                  UnprocessableEntity(JsError.toJson(e))
          }
  }
}

问题是,行:

case e: JsError => UnprocessableEntity(JsError.toJson(e))

以这种格式产生错误:

{
    "obj.user": [
        {
            "msg": [
                "error.path.missing"
            ],
            "args": []
        }
    ],
    "obj.password": [
        {
            "msg": [
                "error.path.missing"
            ],
            "args": []
        }
    ]
}

而不是:

{"errors": ["User was not provided", "Password was not provided"]}

是否存在我缺少的内置/简单方法,将错误转换为更易读的方式?至少将error.path.missing转换为was not provided之类的内容?或者我自己需要写这个?

1 个答案:

答案 0 :(得分:0)

这些方面应该有用......

[编辑]

while