2016-07-12 45 views
0

彈性搜索拋出由IndexAlreadyExists異常引起的RemoteTransportException。如何確定異常是否由特定的其他異常引起?

我想忽略這種情況,但仍然要確保發現可能發生的其他異常。

爲此,我實現了一個功能,以確定是否異常是由另一個異常引起的:

private def exceptionCausedBy[T](e: Throwable): Boolean = { 
    // scalastyle:off null 
    e.isInstanceOf[T] || (e.getCause != null && exceptionCausedBy[T](e.getCause)) 
    } 

我稱之爲像這樣:

... 
case e: Throwable if exceptionCausedBy[IndexAlreadyExistsException](e) => 
... 

然而這給了警告:

abstract type T is unchecked since it is eliminated by erasure 
e.isInstanceOf[T] || (e.getCause != null && exceptionCausedBy[T](e.getCause)) 
      ^

這是有道理的,因爲類型T在編譯時已知並被擦除由編譯器。

添加ClassTag就足夠嗎?

def exceptionCausedBy[T: ClassTag](e: Throwable): Boolean = { 
    // scalastyle:off null 
    e.isInstanceOf[T] || (e.getCause != null && exceptionCausedBy[T](e.getCause)) 
} 

我在IDEA測試Scratchfile似乎也印證了這一點,但我希望得到一些專家的意見。

此外,如果這是要對這個完全愚蠢的方式,請不要猶豫,指出它:)

+0

至少這聽起來合乎邏輯:) – ipoteka

回答

1

isInstanceOf[T]檢查不使用ClassTag,匹配: T一樣。所以它應該是

def exceptionCausedBy[T: ClassTag](e: Throwable): Boolean = e match { 
    // scalastyle:off null 
    case null => false 
    // scalastyle:on null 
    case _: T => true 
    case _ => exceptionCausedBy[T](e.getCause) 
} 
+0

太好了,這似乎是伎倆。你能幫我理解':Classtag'在這裏的作用究竟是什麼? – mirosval

+0

搜索「斯卡拉上下文綁定」,有很多解釋(都在SO特別是在互聯網上)。 –

相關問題