2

Currently I handle javax.persistence.PersistenceException by checking the StackTrace for the occurrence of a constraint name defined in a annotation.

Is there any more elegant way to solve the problem?

Spring Validation makes it quite easy as the ConstraintViolationExceptiongives me the Property Name and the Message defined in the constraint.

3
  • No. Because what message you get on a constraint violation is database product dependent. What database are you using? Commented Dec 30, 2017 at 17:01
  • I'm currently using H2 for testing. Later MySQL or Postgres. But I want to keep it independent from the database implementation. I guess most databases will at least return the name of the violated constraint. Commented Dec 31, 2017 at 10:41
  • Yes usually if they have meaningful names. But at the end the implementation is custom anyway Commented Jan 2, 2018 at 9:55

1 Answer 1

1

You can use Controller Based Exception Handling. https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc#controller-based-exception-handling

 @ResponseStatus(value=HttpStatus.CONFLICT,
                  reason="Data integrity violation")  // 409
  @ExceptionHandler(DataIntegrityViolationException.class)
  public void conflict() {
    // Nothing to do
  }
Sign up to request clarification or add additional context in comments.

1 Comment

I'm actually using Controller Based Excption Handling returning a custom object containing detailed information about the violation (which field, etc). The point of my question is how to best map the database error message to a user-friendly error message.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.