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;
}
}
I think that any error that is thrown by oracle will be wrapped in a SQLException (somebody please correct me if wrong). Once you have accessed the SQLException you should be able to call
getErrorCode() Retrieves the vendor-specific exception code for this SQLException object.
Let me know if this works as I have never tried it :-)
Karl
You could improve your code checking for SQLException
Also, I think in Oracle "errCode" contains the number associated to ORA-nnnn
If the exception being thrown is always going to be of a specific type, like OracleException, you can catch just that exception.
For example:
This would only apply if there are specific Oracle exceptions being thrown. I don't know much about Oracle, so before attempting this you will probably want to find out if that's what's happening.
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!)
Probably a bit overkill for your usage but I think it is cleaner (and reusable)
you can use the getStackTrace() from the Throwable class. This would give you the stack of StackTraceElements to work with. You can iterate through the StackTraceElements[] to find "ORA" string.Let me know if you need an example.