How to get the name of the key while handling DataIntegrityViolationException?

Viewed 126

I'm using GenericExceptionHandling on the application level

@ControllerAdvice
public class GlobalExceptionHandler {
    
    // Handle the DataIntegrityViolationException
    @ExceptionHandler(DataIntegrityViolationException.class)
    public ResponseEntity<?> customDataIntegrityViolationException
                                (DataIntegrityViolationException exception) {
        String message = "This {key} is already exist";
        ErrorDetails errorDetals = new ErrorDetails(new Date(), message, exception.getCause().getMessage());
        return new ResponseEntity<Object>(errorDetals, HttpStatus.UNPROCESSABLE_ENTITY);
    }
}

I want to get the name of the key that's causing the error. I.e. {key}. I googled but didn't get any answer that solves my problem. If anyone has done this kind of work please suggest a way.

1 Answers

I guess you should search for the exception message, e.g

      try{
            userRepository.save(user);
        }
        catch (DataIntegrityViolationException ex){

            if(ex.getMessage().contains("unique_username")){
                throw new DataIntegrityViolationException("The username: "+user.getUsername()+" is duplicated");
            }
            else if(ex.getMessage().contains("unique_email")){
                throw new DataIntegrityViolationException("The email: "+user.getEmail()+" is duplicated");
            }

            else {
                throw new DataIntegrityViolationException(ex.getMessage());
            }

        }

for better searching the constraint you can specify constraint name e.g

@Entity
@Table(name = "user_tbl",
uniqueConstraints = {@UniqueConstraint(columnNames ="username", name = "unique_username"),
               
                    @UniqueConstraint(columnNames ="email", name = "unique_email")})


public class User {

    String username;
    String email;
    .
    .
    .
    
}
Related