Skip to content

Instantly share code, notes, and snippets.

@EdgeCaseBerg
Forked from fancellu/ExceptionDig.scala
Last active August 29, 2015 14:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EdgeCaseBerg/594646d75d548cf107ec to your computer and use it in GitHub Desktop.
Save EdgeCaseBerg/594646d75d548cf107ec to your computer and use it in GitHub Desktop.
// Using vars, lots of local mutation
def getThemVar(th:Throwable)={
var now=th
var li=List[Throwable](now)
var cause=now.getCause
while (cause!=null){
li=cause::li
now=cause
cause=now.getCause
}
li.reverse.toVector
}
// Using recursion and tailrec so as not to blow the stack
def getThemTailRec(th:Throwable)={
@scala.annotation.tailrec
def inner(th:Throwable,v:Vector[Throwable]):Vector[Throwable]={
val tail=v:+th
if (th.getCause==null) tail else inner(th.getCause,tail)
}
inner(th,Vector[Throwable]())
}
// simple recursion, might blow stack if exception VERY deep
def getThemSimpleRecurse(th:Throwable):Vector[Throwable]=
Vector[Throwable](th) ++ (if (th.getCause==null) Nil else getThemSimpleRecurse(th.getCause)
// Using the power of Iterator.iterate, will give you iterator of ha and all causes
def getIterate(ha:Throwable)=
Iterator.iterate(ha)(_.getCause).takeWhile(_!=null).toVector
val ha:Throwable=new Exception(new Throwable("I have gone bang",new Exception("I am the cause")))
// All emit
// Vector(java.lang.Exception: java.lang.Throwable: I have gone bang, java.lang.Throwable: I have gone bang, java.lang.Exception: I am the cause)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment