1

Working on an api call which alters some data in DB.I am trying to provide a meaningful message from api in case there is an exception in JPA Layer. On any sql query run failure I get DataIntegrityViolationException from JPA which does not contain the exact reason of failure. Hence I am extracting the SQLException from it and then responding with the error message.

private String getSQLExceptionMessage(DataIntegrityViolationException e) {
    Throwable nextException = e.getCause();
    while (!nextException.getClass().equals(SQLException.class) && nextException.getCause() != null
            && !nextException.getClass().equals(nextException.getCause().getClass())) {
        nextException = nextException.getCause();
    }
    return nextException.getMessage();
}

Is there any better way to do this?

2
  • How do you plan to handle failure in your API? Throw the original exceptions, wrap them in your own exception type, ... ? Commented May 3, 2018 at 17:55
  • I have a list of error field in response, I was thinking to respond with 500 status code and fill in the error field with the list of messages. Commented May 4, 2018 at 3:27

2 Answers 2

3

There is an utility class NestedExceptionUtils in Spring, which getMostSpecificCause method you can use to get the 'root' cause of any exception.

Regarding the error handling - you can implement a custom exception handler for DataIntegrityViolationException, extract the constraint name from the root cause, analyze it and create a corresponding message for the user.

Some error handling examples: 1, 2.

Sign up to request clarification or add additional context in comments.

1 Comment

The problem with using NestedExceptionUtils.getMostSpecificCause is that it is giving the me the last SQLException in the getCause() chain which does not have the proper error message. However the first SQLException in the getCause() chain has the correct root cause message.
1

Yeah you can use NestedExceptionUtils in Spring to get root course for any exception. Sample code below

 try {
          //your code
    
      } catch (DataIntegrityViolationException e){
          throw new DataIntegrityViolationException(NestedExceptionUtils.getMostSpecificCause(e).getMessage());
      }

Comments

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.