Handling SQL Integrity Constraint Violation Exceptions
This tutorial will guide you through handling `SQLIntegrityConstraintViolationException` when persisting objects that violate database constraints.
Step 1: Catch the EJB Exception
Catch a `javax.ejb.EJBException` which wraps the underlying exception.
try {
// persistence transactions
} catch (Exception e) {
if (e instanceof javax.ejb.EJBException) {
logger.debug("Exception instance of javax.ejb.EjbException");
}
}
Step 2: Get the Underlying Exception
Get the underlying exception from the `EJBException` using `e.getCause()`.
try {
// persistence transactions
} catch (Exception e) {
if (e instanceof javax.ejb.EJBException) {
logger.debug("Exception instance of javax.ejb.EjbException");
Throwable cause = e.getCause();
if (cause != null) {
cause = cause.getCause();
if (cause instanceof org.hibernate.exception.ConstraintViolationException) {
// Handle ConstraintViolationException
}
}
} else {
e.printStackTrace();
}
}
Step 3: Check for Constraint Violation Exception
Check if the underlying exception is an instance of `ConstraintViolationException`.
try {
// persistence transactions
} catch (Exception e) {
if (e instanceof javax.ejb.EJBException) {
logger.debug("Exception instance of javax.ejb.EjbException");
Throwable cause = e.getCause();
if (cause != null) {
cause = cause.getCause();
if (cause instanceof org.hibernate.exception.ConstraintViolationException) {
// Handle ConstraintViolationException
logger.info("update_duplicate_response | " + update_response);
}
}
} else {
e.printStackTrace();
}
}
Remember
* Catch `javax.ejb.EJBException` to handle the underlying exception.
* Use `e.getCause()` to get the underlying exception.
* Check if the underlying exception is an instance of `ConstraintViolationException`.
* Handle the exception accordingly.
Happy coding.
Comments
Post a Comment