如何使用Swagger生成的客户端代码从REST API接收错误消息/异常?

时间:2018-11-12 05:03:32

标签: swagger swagger-2.0 swagger-codegen

下面是Swagger Codegen生成的Scala代码段。

  def v4TestPostCheck(payload: TestResourceEntityRequest ): Option[TestResource] = {
    val await = Try(Await.result(v4TestPostAsync(payload), Duration.Inf))
    await match {
      case Success(i) => Some(await.get)
      case Failure(t) =>  None
    }
  }

  def v4TestPostAsync(payload: TestResourceEntityRequest): Future[TestResource] = {
    helper.v4TestPost(payload)
  }


  def v4TestPost(payload: TestResourceEntityRequest)(implicit reader: ClientResponseReader[TestResource], writer: RequestWriter[TestResourceEntityRequest][]): Future[TestResource] = {
    // create path and map variables
    val path = (addFmt("/v4/test"))

    // query params
    val queryParams = new mutable.HashMap[String, String]
    var headerParams = new mutable.HashMap[String, String]

    headerParams = ApiInvoker.defaultHeaders
    val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, writer.write(payload))
    resFuture flatMap { resp =>
      println("response:"+resp.status)
      println(resp.body)
      println(resp.statusText) // this is printing the error message sent by Service, but how to return this message from this method
      println(resp.uri)

      Try {process(reader.read(resp))} match {
        case Success(obj) => obj
        case Failure(_) => throw new Exception("")
      }
    }

  }

对于成功案例,此代码成功接收了TestResource对象。 但是,如果发生任何错误/ BadRequest,它将接收空的TestResource对象。 相反,它应该报告Service抛出的错误消息。 我们如何使用昂首阔步的代码捕获这些消息?

0 个答案:

没有答案