2007-03-21

SQL Constraint Violations

Here is a snippet that will identify whether a given Java exception is caused by an SQL constraint violation:

private static boolean isConstraintViolationException(Exception exception) {
    for (Throwable cause = exception; null != cause; cause = cause.getCause()) {
        if (cause instanceof SQLException) {
            String sqlState = ((SQLException)cause).getSQLState();
            if (null != sqlState && sqlState.startsWith("23")) {
                return true;
            }
        }
    }
    return false;
}

The black magic is bolded.  All of the SQLSTATE values in the 23xxx block represent some form of constraint violation.  Many databases simply return 23000 which indicates a non-specific type of violation.