`transformWith [Array [Byte]]`里面的`Future.failed`给出了编译错误

问题描述 投票:0回答:1

我试图分析来自Akka的HttpResponse。理想的行为是,如果响应成功返回,则传递Array[Byte]HttpEntity表示以进行处理。但是,如果状态返回为失败,则传递带有异常的Future.failed,其中包含状态代码和HttpEntity的JSON树表示。传递JSON树的原因是这个抽象请求方法有不同的服务器,并且它们的响应格式不同,所以我想在其他类中处理响应的解析。

我尝试过对这个工作流程的各种操作。直接抛出异常而不是返回Future.failed会返回None值来代替异常中的JSON树。其他方法产生类似的结果。当我println(MAPPER.readTree(byteArray))它按照我的预期打印出响应,但然后继续返回NoneresponseBadRequestException字段。

import akka.http.scaladsl.model._
import akka.http.scaladsl.model.headers.Authorization
import akka.stream.Materializer
import com.fasterxml.jackson.databind.{DeserializationFeature, JsonNode, ObjectMapper}
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.module.scala.experimental.ScalaObjectMapper

val MAPPER = new ObjectMapper with ScalaObjectMapper
  MAPPER.registerModule(DefaultScalaModule)
  MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)

def performQueryRaw(method: HttpMethod, uri: Uri, entity: Option[RequestEntity] = None, authorization: Option[Authorization] = None): Future[Array[Byte]] = {

  val request: HttpRequest = HttpRequest(
    method = method,
    uri = uri,
    entity = entity.getOrElse(HttpEntity.Empty),
    headers = authorization.toList)

  http.singleRequest(request).transformWith[Array[Byte]] {
    case Success(response: HttpResponse) =>
      convertEntityToBytes(response.entity).map { byteArray =>
        if (response.status.isFailure()) Future.failed(BadRequestException(response.status, MAPPER.readTree(byteArray)))
        else byteArray
      }
      case Failure(throwable) => Future.failed(RequestFailedException(throwable.getMessage + " -- " + uri.toString, throwable))
    }
  }

def convertEntityToBytes(entity: HttpEntity): Future[Array[Byte]] = {
  entity.dataBytes.runFold[Seq[Array[Byte]]] (Nil) {
    case (acc, next) => acc :+ next.toArray
  }.map(_.flatten.toArray)
}

case class BadRequestException(status: StatusCode, response: JsonNode = None.orNull, t: Throwable = None.orNull) extends Exception(t)

case class RequestFailedException(message: String, t: Throwable = None.orNull) extends Exception(message, t)

我期待一个BadRequestException输出JsonNode的非none值。相反,我在Future.failed上遇到编译器错误:

Expression of type Future[Nothing] doesn't conform to expected type Array[Byte]

任何帮助将不胜感激。

scala akka future akka-http jackson-databind
1个回答
1
投票

flatMap之后运行下一步时使用map而不是convertEntityToBytes

def performQueryRaw(
    method: HttpMethod,
    uri: Uri,
    entity: Option[RequestEntity] = None,
    authorization: Option[Authorization] = None
  ): Future[Array[Byte]] = {

    val request: HttpRequest = HttpRequest(
      method = method,
      uri = uri,
      entity = entity.getOrElse(HttpEntity.Empty),
      headers = authorization.toList
    )

    Http().singleRequest(request).transformWith[Array[Byte]] {
      case Success(response: HttpResponse) =>
        convertEntityToBytes(response.entity).flatMap { byteArray =>
          if (response.status.isFailure()) Future.failed(new Exception("change this exception to one you had"))
          else Future.successful(byteArray)
        }
      case Failure(throwable) => Future.failed(new Exception("also here"))
    }
  }

既然你想失败你Future计算,你需要返回新的Future。如果失败,你一直在做Future.failed。缺少的部分也是将一个byteArray包装到Future.successful。当然这是解决此代码中类型编译错误的方法之一。

© www.soinside.com 2019 - 2024. All rights reserved.