Any idea why this code doesn't work? I'm trying to have serialize
method to all my exceptions to avoid the need for pattern matching for every exception. With the code below, I just need to case ex:MarshallableException => ex.serialize
The below code can run stand-alone. It will print 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)
}
}