Matching by nested exception type

I am using some client library and had some code that ignored a specific exception using scala.util.control.Exception.ignoring :

 ignoring(classOf[ReallyNotThatExceptionalException]) { stuff() } 

Now this library has changed to wrap all exceptionn in a different exception class, which forced me to change the code to this:

 try { stuff() } catch { case e:WrapperException if e.getCause != null && e.getCause.isInstanceOf[ReallyNotThatExceptionalException] => { } } 

So I'm looking for a more readable way to express "catch exceptions thrown".

+5
source share
2 answers

The 0__ answer is good, but it would be better if you were not forced to write a specific object ( CausedByFoo ) for each potential exception. As it happens, there is nothing to change to get a common CausedBy helper object:

 class Foo(message: String) extends Exception(message) class Bar(cause: Throwable) extends Exception(cause) object CausedBy { def unapply(e: Throwable): Option[Throwable] = Option(e.getCause) } def test(block: => Unit): String = try { block "ok" } catch { case CausedBy(ex: Foo) => "not ok: " + ex.getMessage } test(println("hello")) test(println("hello".toInt)) // uncaught exception test(throw new Bar(new Foo("Ooops, foo error!"))) // caught 

As should be obvious, you can use CausedBy with any exception (for example, by running case CausedBy(ex: Baz) .

You can even nest it to handle an exception caused by an exception caused by an exception (by doing something like case CausedBy(CausedBy(ex: Foo))

+10
source

The catch can handle any regular pattern match, so

 class Foo extends Exception class Bar(cause: Exception) extends Exception(cause) object CausedByFoo { def unapply(e: Exception): Boolean = e.getCause match { case _: Foo => true case _ => false } } def test(block: => Unit): String = try { block "ok" } catch { case CausedByFoo() => "not ok" } test(println("hello")) test(println("hello".toInt)) // uncaught exception test(throw new Bar(new Foo)) // caught 
+4
source

Source: https://habr.com/ru/post/1208892/


All Articles