处理 JSON 播放应用中第三方服务的解析错误

Handling JSON parse errors of third party services in play applications

考虑到反序列化错误,我想知道从第三方服务解析 JSON 的可接受方法是什么。

比如这个服务方式:

  def signInWithEmailAndPassword(email: String, password: String): Future[ApiResponse[SignInResponse]] =
    request("/signin").post(Json.obj("email" -> email, "password" -> password))
      .map(_.json.as[ApiResponse[SignInResponse]])

如果 json.as 失败,将抛出服务器异常,播放将在默认错误处理程序中捕获。

这样的客户端结构可以吗?似乎 JSON 解析错误无论如何都无法真正恢复,所以使用通用错误处理程序是否合适?

这里有一些示例可以帮助您入门。这是您通常在 Play 框架控制器中编写的方法。

def dispatchPowerPlant(id: Int) = Action.async(parse.tolerantJson) { request =>
    request.body.validate[DispatchCommand].fold(
      errors => {
        Future.successful{
          BadRequest(
            Json.obj("status" -> "error", "message" -> JsError.toJson(errors))
          )
        }
      },
      dispatchCommand => {
        actorFor(id) flatMap {
          case None =>
            Future.successful {
              NotFound(s"HTTP 404 :: PowerPlant with ID $id not found")
            }
          case Some(actorRef) =>
            sendCommand(actorRef, id, dispatchCommand)
        }
      }
    )
  }

所以它所做的是检查 JSON 有效负载的有效性并相应地发送响应!希望这对您有所帮助!

您可能有类似的设置来相应地验证 JSON 和 return 响应。

假设 ApiResponse 将保留任何客户端错误(密码错误等),而 Future 将保留服务器错误(无法建立连接、来自远程服务的 500 等) ( =]ing).