【问题标题】:Handling JSON parse errors of third party services in play applications处理 play 应用中第三方服务的 JSON 解析错误
【发布时间】:2018-01-04 08:49:56
【问题描述】:

考虑到反序列化错误,我想知道从第三方服务解析 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 解析错误无论如何都无法真正恢复,因此使用通用错误处理程序是否合适?

【问题讨论】:

    标签: scala playframework ws-client


    【解决方案1】:

    这里有一些示例可以帮助您入门。这是您通常在 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 并相应地返回响应。

    【讨论】:

      【解决方案2】:

      假设ApiResponse 将保留任何客户端错误(密码错误等)并且Future 将保留服务器错误(无法建立连接、来自远程服务的 500 等),那么是的,它是合适的Future 中的异常冒泡到错误处理程序并向调用者返回 500(还假设在返回之前没有需要清理的资源)。

      【讨论】:

      • 谢谢!是的,我就是这么想的——因为那时它不一定可以恢复。希望我能深入阅读一些关于这个主题的固执己见
      猜你喜欢
      • 2017-12-04
      • 1970-01-01
      • 2012-12-13
      • 2012-06-11
      • 2018-04-22
      • 1970-01-01
      • 2023-03-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多