2013-08-20 12 views
5

Sto cercando di trovare il modo più semplice ma corretto per estendere Java Exception in Scala. Ad esempio, il seguente non è corretto perché new Exception(null, cause) e new Exception(cause) avere un comportamento differente a seconda Throwable.java:Qual è il modo migliore per estendere correttamente un'eccezione Java in Scala?

class InvalidVersionException(message: String = null, cause: Throwable = null) 
    extends IllegalArgumentException(message, cause) { 
    def this(message: String) = this(message, null) 
    // This is not same with super(cause) 
    def this(cause: Throwable) = this(null, cause) 
} 

Perché so Throwable(cause) imposta il messaggio di cause.toString(), mi si avvicinò con il seguente:

class InvalidVersionException(message: String = null, cause: Throwable = null) 
    extends IllegalArgumentException(if ((message eq null) && (cause ne null)) cause.toString else message, cause) { 
    def this(message: String) = this(message, null) 
    def this(cause: Throwable) = this(null, cause) 
} 

Tuttavia, questo ha ancora:

if ((message eq null) && (cause ne null)) cause.toString 

che è stato duplicato da Throwable.java.

Esiste un modo migliore per estendere uno Exception senza la duplicazione del codice?

risposta

0

Sulla base della risposta da @Shadowlands, ho finito con il seguente:

class InvalidVersionException(message: String, cause: Throwable = null) 
    extends IllegalArgumentException(message, cause) { 
    def this(cause: Throwable) = this(if (cause ne null) cause.toString else null, cause) 
    def this() = this(null) 
} 

.. che permette di risparmiare 54 byte.

2

Sembra a me come si dovrebbe essere in grado di cambiare solo il costruttore di causa-solo:

def this(cause: Throwable) = this(cause.toString, cause) 

EDIT: Per gestire causa nullo:

def this(cause: Throwable) = this(if (cause == null) "(no message)" else cause.toString, cause) 

sostituire "(nessun messaggio) "con null (non consigliato) o qualunque testo tu ritenga appropriato.

+0

Solleverà un 'NullPointerException' se' causa' è 'null'. – trustin

+0

@trustin Fair point. Ho modificato la mia risposta con un modo per affrontarlo. – Shadowlands

0

Che ne dici di questo?

trait InvalidVersionException extends IllegalArgumentException 

object InvalidVersionException { 
    def apply(msg: String) = new IllegalArgumentException(msg) with InvalidVersionException 
    def apply(cause: Throwable) = new IllegalArgumentException(cause) with InvalidVersionException 
    def apply(msg: String, cause: Throwable) = new IllegalArgumentException(msg, cause) with InvalidVersionException 
} 

(tramite "In Scala, how can I subclass a Java class with multiple constructors?")

+0

Non sono sicuro se sia una buona idea rendere un'eccezione un tratto. Non significa davvero che una classe a caso può estenderla? – trustin

Problemi correlati