1

I'm used to check if the user try to store a valid data with cathcing the ConsratinViolationException, like that:

try {
    //persisitng to a db
} 
catch (ConstraintViolationException e){
    //Print message
}

I'm using PostgreSQL and now I'm under the isssue that the persisitng can violate more than one different constarints. How can I distiguish in the catch clause what exactly constraint has been violated?

I need to do that, because the message the programm will print depending on that.

St.Antario
  • 26,175
  • 41
  • 130
  • 318
  • Try this: http://stackoverflow.com/questions/3495926/can-i-catch-multiple-java-exceptions-in-the-same-catch-clause – Simon Jun 15 '15 at 09:36

2 Answers2

3

something like below

catch (ConstraintViolationException conEx) {
            if (conEx.getConstraintName().contains("xyz_fK")) {
                //TODO Project Entity is violating it's constrain
            } 
            LOGGER.Info( "My log message", conEx.getConstraintName());
            LOGGER.ERROR( "My log message", conEx);
Ankur Singhal
  • 26,012
  • 16
  • 82
  • 116
2

A ConstraintViolationException contains a Set of ConstraintViolations. Each of it contains information about a single violation. You can retrieve this Set with getConstraintViolations() and then iterate over it to find out, what has gone wrong in detail.

See http://docs.oracle.com/javaee/7/api/javax/validation/ConstraintViolationException.html.