Wednesday, September 7, 2011

How to access "internal exception" type in JAVA

how to catch MySQLIntegrityConstraintViolationException exception


Suppose JPA entry is:

@Table(name = "players", uniqueConstraints=@UniqueConstraint(columnNames={"firstname", "lastname"}))


EJB class is:
public void create(Player player) {
try {
em.persist(player);
em.flush();
} catch (Exception e) {
e.printStackTrace();
Throwable t = getLastThrowable(e);
throw new Exception(t);
}
}



/** method to access internal exceptions */

private Throwable getLastThrowable(Exception e) {
Throwable t = null;
for(t = e.getCause(); t.getCause() != null; t = t.getCause());
return t;
}