[英]Scala, Circe, Http4s - is it any way to encode Throwable in Circe?
I have created hierarchy of errors:我创建了错误层次结构:
sealed trait MyError extends Throwable
final case class SecondError(msg: String) extends MyError
Now I could get this kind of error in my http4s
routes:现在我可以在我的
http4s
路由中得到这种错误:
case GET -> Root / "things" => for {
response <- things.all.foldM(
error => error match {
case SecondError(_) => InternalServerError(error)
}
...
But I get compiled error:但我得到编译错误:
could not find implicit value for parameter encoder: io.circe.Encoder[Throwable]
Is it possible to encode Throwable
with circe
and http4s
?是否可以使用
circe
和http4s
对Throwable
进行编码? I tried to do it this way:我试图这样做:
implicit def encoderHttpThrowable: EntityEncoder[Env, Throwable] = jsonEncoderOf[Env, Throwable]
But it did not solve a problem.但它并没有解决一个问题。
It is not possible to encode automatically a Java Hierarchy with Circe (or any other library) (I am pretty sure of this).不可能使用Circe (或任何其他库)自动编码 Java 层次结构(我很确定这一点)。
So you have 3 possibilities:所以你有3种可能性:
Just use the Message of the error:只需使用错误消息:
case GET -> Root / "things" => things.all.foldM ( error => InternalServerError(error.getMessage()), Ok(_) )
Or get rid of the Throwable:或者摆脱 Throwable:
sealed trait MyError final case class SecondError(msg: String) extends MyError
And now you can encode the error现在您可以对错误进行编码
... case GET -> Root / "things" => things.all.foldM ( error => InternalServerError(error), Ok(_) )
Map your Throwable to your own Error (Sealed Trait without Throwable):将您的 Throwable 映射到您自己的错误(没有 Throwable 的密封特征):
... case GET -> Root / "things" => things.all .mapError{ case ex: IllegalArgumentException => SecondError(ex.getMessage) case ex => FirstError(ex.getMessage) } .foldM ( error => InternalServerError(error), Ok(_) )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.