I am trying to call saveOrUpdate()
in hibernate to save data. Since columns have unique index, so its throws ConstraintViolationException
when I look through via Eclipse debugger.
Since root cause could be different for different exception while inserting data to table.
I wanted to know, how can I loop / traverse through getCause()
to check what is the root cause of exception and its message.
Update:
Thanks everyone for your kind response, thing is I want output like in below image:
I need to access detailMessage field.
(I am really sorry If could not make my question more clear.)
Thanks.
The getCause() method of Throwable class is the inbuilt method used to return the cause of this throwable or null if cause can't be determined for the Exception occurred. This method help to get the cause that was supplied by one of the constructors or that was set after creation with the initCause(Throwable) method.
Chained exceptions helps in finding the root cause of the exception that occurs during application's execution. The methods that support chained exceptions are getCause(), initCause() and the constructors Throwable(Throwable), Throwable(String, Throwable).
When an exception is chained, the getCause method is used to get the original cause. In this case, the exception was not chained from any other layer, hence getCause returns null .
The Apache ExceptionUtils provide the following method:
Throwable getRootCause(Throwable throwable)
as well as
String getRootCauseMessage(Throwable th)
I normally use the implementation below instead of Apache's one.
Besides its complexity, Apache's implementation returns null when no cause is found, which force me to perform an additional check for null.
Normally when looking for an exception's root/cause I already have a non-null exception to start with, which is for all intended proposes is the cause of the failure at hand, if a deeper cause can't be found.
Throwable getCause(Throwable e) {
Throwable cause = null;
Throwable result = e;
while(null != (cause = result.getCause()) && (result != cause) ) {
result = cause;
}
return result;
}
Using java 8 Stream API, this can be achieved by:
Optional<Throwable> rootCause = Stream.iterate(exception, Throwable::getCause)
.filter(element -> element.getCause() == null)
.findFirst();
Note that this code is not immune to exception cause loops and therefore should be avoided in production.
Are you asking for something like this?
Throwable cause = originalException;
while(cause.getCause() != null && cause.getCause() != cause) {
cause = cause.getCause();
}
or am I missing something?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With