[英]How to get data inside a Throwable Scala object?
How I get information inside a Throwable
Scala object? 如何在
Throwable
Scala对象中获取信息?
The code is an example about throwable.getMessage
. 该代码是有关
throwable.getMessage
的示例。
JsResultException(errors:List((,List(JsonValidationError(List('eoh' is undefined on object: {"store":"8767565","sku":"1983278364782364782"}),WrappedArray())))))
I need to extract JsResultException
, JsonValidationError
as string, message 'eoh' is undefined on object
message and JSON before object:
. 我需要将
JsResultException
, JsonValidationError
提取为字符串, 'eoh' is undefined on object
message和JSON object:
之前'eoh' is undefined on object
消息'eoh' is undefined on object
。
Is this for make graceful log. 这是使优美的日志。
Consider converting JsResultException.errors
which is 考虑将
JsResultException.errors
转换为
Seq[(JsPath, Seq[JsonValidationError])]
where JsonValidationError.errors
is yet another sequence Seq[String]
, into a simpler tuple 其中
JsonValidationError.errors
是另一个序列Seq[String]
,成为一个更简单的元组
Seq[(JsPath, String)]
like so 像这样
case JsResultException(errors) =>
errors.map { case (path, validationErrors) => path -> validationErrors.map(_.messages.mkString(",")).mkString(",") }
This would produce a more managable structure similar to 这将产生更易于管理的结构,类似于
List((/id,error.path.missing), (/name,error.path.missing))
instead of 代替
List((/id,List(JsonValidationError(List(error.path.missing),WrappedArray()))), (/name,List(JsonValidationError(List(error.path.missing),WrappedArray())))))]
Here is a working example 这是一个有效的例子
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(",") }
}
Also consider using validation to avoid throwing exceptions like so 还可以考虑使用验证来避免像这样抛出异常
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(",") }
}
You can always use the scala.util.Try and pattern match the Failure. 您可以始终使用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 => ???
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.