如何以抽象方式使用Spray JSON序列化程序?

时间:2015-11-18 16:26:05

标签: scala akka-http

知道为什么这段代码不起作用?我正在尝试对所有异常使用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)
  }
}

0 个答案:

没有答案