Scala:错误处理和异常匹配

时间:2014-08-22 18:23:30

标签: scala

鉴于以下自定义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收到错误消息?

2 个答案:

答案 0 :(得分:3)

您所描述的匹配工作需要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")
}

答案 1 :(得分:0)

人们喜欢案例类。

这并不完全符合您的数量,但例如:

scala> trait ServiceException { _: RuntimeException => def errorCode: Int }
defined trait ServiceException

scala> case class MyX(errorCode: Int, msg: String, cause: Exception = null) extends RuntimeException(msg, cause) with ServiceException
defined class MyX

scala> def i: Int = throw MyX(42, "Help!")
i: Int

scala> import concurrent._ ; import ExecutionContext.Implicits._
import concurrent._
import ExecutionContext.Implicits._

scala> Future(i) recover { case MyX(code, m, err) => println(m) ; -1 }
res11: scala.concurrent.Future[Int] = scala.concurrent.impl.Promise$DefaultPromise@7d17ee50

scala> Help!

scala> .value
res12: Option[scala.util.Try[Int]] = Some(Success(-1))