0

知道为什么这段代码不起作用吗?我试图对serialize所有异常都有方法,以避免对每个异常都进行模式匹配。使用下面的代码,我只需要case ex:MarshallableException => ex.serialize

下面的代码可以独立运行。它将打印Start... Serialization Failure shared.utils.InvalidID:(

import scala.util.{Failure, Success}
import akka.http.scaladsl.marshalling.{Marshaller, Marshal}
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._
import akka.http.scaladsl.model.ResponseEntity
import spray.json.DefaultJsonProtocol
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global


trait MarshallableException{
  def serialize: Future[ResponseEntity]
}

case class InvalidID(error:String, code: String= "6001")  extends Exception with MarshallableException {
  import Exceptions._

  override def serialize: Future[ResponseEntity] = {
    Marshal(this).to[ResponseEntity]
  }
}

object Exceptions extends DefaultJsonProtocol{

  implicit val invalidIDFormat = jsonFormat2(InvalidID.apply)

}

object Test extends App{
  val ex = new InvalidID("Test exception")
  println("Start...\n")
  ex.serialize.onComplete{
    case Success(e) => println(e.toString())
    case Failure(f) =>
      println("Serialization Failure " + f.toString)
  }
}
4

0 回答 0