我如何在Throwable
Scala对象中获取信息?
该代码是有关throwable.getMessage
的示例。
JsResultException(errors:List((,List(JsonValidationError(List('eoh' is undefined on object: {"store":"8767565","sku":"1983278364782364782"}),WrappedArray())))))
我需要提取JsResultException
,JsonValidationError
作为字符串,消息'eoh' is undefined on object
消息和JSON,然后提取object:
。
这是用来制作优美的日志吗?
答案 0 :(得分:2)
考虑将JsResultException.errors
转换为
Seq[(JsPath, Seq[JsonValidationError])]
其中JsonValidationError.errors
是另一个序列Seq[String]
,进入一个更简单的元组
Seq[(JsPath, String)]
像这样
case JsResultException(errors) =>
errors.map { case (path, validationErrors) => path -> validationErrors.map(_.messages.mkString(",")).mkString(",") }
这将产生更易于管理的结构,类似于
List((/id,error.path.missing), (/name,error.path.missing))
代替
List((/id,List(JsonValidationError(List(error.path.missing),WrappedArray()))), (/name,List(JsonValidationError(List(error.path.missing),WrappedArray())))))]
这是一个可行的例子
case class User(name: String, id: Int)
object User {
implicit val formats = Json.format[User]
}
val raw = """{ "nam": "mario", "i": 5 }"""
try {
Json.parse(raw).as[User]
} catch {
case JsResultException(errors) =>
errors.map { case (path, validationErrors) => path -> validationErrors.map(_.messages.mkString(",")).mkString(",") }
}
也考虑使用using validation以避免抛出类似的异常
Json.parse(raw).validate[User] match {
case s: JsSuccess[User] => s
case JsError(errors) =>
errors.map { case (path, validationErrors) => path -> validationErrors.map(_.messages.mkString(",")).mkString(",") }
}
答案 1 :(得分:0)
您始终可以使用scala.util.Try和Pattern匹配Failure。
import scala.util._
def someExceptionThrowingMethod(): T = ???
Try(someExceptionThrowingMethod()) match {
case Success(t: T) => ???
case Failure(exception: Throwable) => exception match {
case JsResultException((_, JsonValidationError(headMessage :: _) :: _, _) :: _) =>
//here headMessage is the 'eoh' is undefined on object: {"store":"8767565","sku":"1983278364782364782"} message you wrote above
case otherException: Throwable => ???
}
}