Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - find the first cause of an exception

I need to check if an exception is caused by some database problem. I receive an Exception and check if its cause contains the "ORA" string and return that (something like "ORA-00001"). The problem here is that the exception I receive is nested inside other exceptions, so if I don't find out if it's an oracle exception, I have to check into the cause of that exception and so on. Is there a cleaner way to do this? Is there a way to know the first cause (the deep-nested exception) of a given exception?

My current code looks like this:

private String getErrorOracle(Throwable e){         final String ORACLE = "ORA";         if (e.getCause() != null && e.getCause().toString().contains(ORACLE)){             return e.getCause().toString();         } else if(e.getCause() != null){             return getErrorOracle(e.getCause());         } else {             return null;         }     } 
like image 644
Averroes Avatar asked Nov 24 '09 17:11

Averroes


2 Answers

In the interests of not reinventing the wheel, if you're using Apache Commons Lang, then look at ExceptionUtils.getRootCause().

Is it worth including a library just for that? Maybe not. But if you already have it on your classpath, it's there for you, and note that it does some things that a 'naive' implementation might not do (e.g. deal with cycles in the cause chain... ugh!)

like image 165
Cowan Avatar answered Sep 23 '22 00:09

Cowan


If you are already on Guava than Throwables.getRootCause() comes to the rescue.

like image 36
Nándor Krácser Avatar answered Sep 21 '22 00:09

Nándor Krácser