Last active
December 13, 2023 06:07
-
-
Save fancellu/8cf6781a9d9e1d5ac6cc to your computer and use it in GitHub Desktop.
Various ways to recurse down Exception causes in Scala
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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