How to set message in Scala custom exception?

时间:2017-04-24 17:27:55

标签: scala exception exception-handling

I have the following trait:

trait ServiceException extends Exception {

  val message: String

  val nestedException: Throwable

}

And exceptions which look like this:

case class NoElementFoundException(message: String = "error.NoElementFoundException",
                                        nestedException: Throwable = null) extends ServiceException

The problem is that if I have a method like this:

def bla(exception: Throwable) = exception.getMessage

And I pass this method my NoElementFoundException, then getMessage will return null.

Probably I could easily fix this by removing the trait and just extending from Exception:

case class NoElementFoundException(message: String = "error.NoElementFoundException",
                                            nestedException: Throwable = null) extends Exception(message)

However, is there a way to keep the trait?

3 个答案:

答案 0 :(得分:1)

您需要覆盖类中的getMessage和getCause方法,以返回属性而不是Exception基类中的属性。

case class NoElementFoundException(override val message: String = "error.NoElementFoundException",
                                   override val nestedException: Throwable = null) extends ServiceException {
  override def getMessage: String = message

  override def getCause: Throwable = nestedException
}

答案 1 :(得分:1)

我假设(虽然不确定)你真的不希望你的ServiceException拥有新的公共方法而不是Exception提供的方法(例如getMessage,{{1} })。

如果是这种情况,您可以getCause扩展ServiceException 扩展程序,而无需Exception扩展自己:

ServiceException

答案 2 :(得分:0)

由于Exception已经有消息和原因,我希望这个特性会导致混淆。我用

替换它
trait ServiceException { _: Exception =>
  def message: String = getMessage
  def nestedException: Throwable = getCause
}

或要在所有Throwable上调用这些方法,

implicit class ThrowableExtensions(self: Exception) {
  def message: String = self.getMessage
  def nestedException: Throwable = self.getCause
}

(在这种情况下,如果您仍然想要ServiceException,它将只是一个空标记特征。)