鉴于以下习惯Exception
...
trait ServiceException extends RuntimeException {
val errorCode: Int
}
object ServiceException {
def apply(
message: String, _errorCode: Int
): ServiceException = new RuntimeException(message) with ServiceException {
val errorCode: Int = _errorCode
}
def apply(
message: String, cause: Throwable, _errorCode: Int
): ServiceException = new RuntimeException(message, cause) with ServiceException {
val errorCode: Int = _errorCode
}
}
...以及以下方法返回Future
...
myService.doSomethingAndReturnFuture.map {
...
}.recover {
case ServiceException(5) =>
Logger.debug("Error 5")
// this does not work
// case e: ServiceException(5) =>
// Logger.debug(s"Error 5: ${e.getMessage}")
case NonFatal(e) =>
Logger.error("error doing something", e)
}
...如何从中获取错误消息ServiceException
?
您需要一个,unapply
以便您描述的匹配项起作用,该匹配项应在伴随对象中定义。
object ServiceException {
//... apply methods
def unapply(ex: ServiceException) = Some(ex.errorCode)
}
然后,您可以进行匹配。
recover {
case se@ServiceException(5) => println(s"Error 5: ${se.getMessage}")
case _ => println("Some other error")
}
您也可以在中添加邮件unapply
。
def unapply(ex: ServiceException) = Some((ex.errorCode, ex.getMessage))
然后像这样匹配:
recover {
case ServiceException(5, msg) => println(s"Error 5: $msg")
case _ => println("Some other error")
}
或者,您也可以不使用unapply
。然后看起来像:
recover {
case se: ServiceException if se.errorCode == 5 => println(s"Error 5: ${se.getMessage}")
case _ => println("Some other error")
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句