2

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.

João Dias
  • 16,277
  • 6
  • 33
  • 45
Karan Talwar
  • 108
  • 6
  • 1
    https://stackoverflow.com/questions/2109476/how-to-handle-dataintegrityviolationexception-in-spring – Rana_S Dec 30 '20 at 17:57

1 Answers1

0

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;
    .
    .
    .
    
}
fatemeakbari
  • 141
  • 2
  • 6