Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How catch hibernate/jpa constraint violations in Spring Boot?

I have been unable to catch ConstraintViolationException (or DataIntegrityViolationException) in ResponseEntityExceptionHandler. I would like to return the jpa failure (e.g. which constraint violated) in the response. (I prefer not to use @Valid on the method parameter and catch handleMethodArgumentNotValid).

...
import org.hibernate.exception.ConstraintViolationException;
import org.springframework.dao.DataIntegrityViolationException;

@ControllerAdvice
public class PstExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler({ConstraintViolationException.class})
    public ResponseEntity<Object> handleConstraintViolation(
        ConstraintViolationException ex, WebRequest request) {

        ...

        return new ResponseEntity<Object>(...);
    }
}

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

@Entity
public class Student {

    @Id
    private Long id;

    @NotNull
    private String name;

    @NotNull
    @Size(min=7, message="Passport should have at least 7 characters")
    private String passportNumber;

    public Student() {
    }

...

}

@RequestMapping(value = "/addstudent"...)
@ResponseBody
public ResponseEntity<Object> addStudent(@RequestBody StudentDto studentDto) {

    Student student = new Student();
    student.setId(studentDto.getId());                          // 1L
    student.setName(studentDto.getName());                      // "helen"
    student.setPassportNumber(studentDto.getPassportNumber());  // "321"

    studentRepository.save(student);

    return ResponseEntity.accepted().body(student);
}

thank you...

like image 466
Helen Reeves Avatar asked Nov 30 '25 10:11

Helen Reeves


1 Answers

Exceptions like ConstraintViolationException are not taken in account because they are extend from HibernateException. you can take a look exceptions in convert method that those are wrapped on Hibernate Exceptions.

@ExceptionHandler({TransactionSystemException.class})
public ResponseEntity<Object> handleConstraintViolation(TransactionSystemException ex, WebRequest request) {

    if (ex.getCause() instanceof RollbackException) {
       RollbackException rollbackException = (RollbackException) ex.getCause();
         if (rollbackException.getCause() instanceof ConstraintViolationException) {
             return new ResponseEntity<Object>(...);
         }
    ...
    }
    ...

    return new ResponseEntity<Object>(...);
}
like image 161
Jonathan JOhx Avatar answered Dec 02 '25 05:12

Jonathan JOhx