2017-04-24 68 views
0

我有以下特點:如何在Scala自定義異常中設置消息?

trait ServiceException extends Exception { 

    val message: String 

    val nestedException: Throwable 

} 

和異常看起來是這樣的:

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

的問題是,如果我有這樣的方法:

def bla(exception: Throwable) = exception.getMessage 

我通過此方法我的NoElementFoundException,然後getMessage將返回null

也許我可以很容易地通過移除特徵和Exception只是擴展解決這個問題:

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

然而,有沒有辦法讓特質?

回答

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

我假設(儘管不知道),你真的不希望你ServiceException s到有比異常(例如getMessagegetCause)提供的那些其他新的公共方法。

如果是這樣的話,就可以讓的ServiceException擴展延伸Exception未做ServiceException擴展它本身:

// "Marker" trait (no methods), extenders must also extend Exception 
trait ServiceException { _: Exception => } 

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

// now you can use Exception.getMessage without "duplicating" it into ServiceException: 
val exception = NoElementFoundException() 
println(exception.getMessage) // prints error.NoElementFoundException 
0

我預計這個特點,因爲它是導致混亂,因爲Exception已經有消息和原因。我會跟

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

取代它,或者開啓所有Throwable s到被調用這些方法,

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

(在這種情況下,如果你還想ServiceException,這將只是一個空標記特徵)。

相關問題