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...
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>(...);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With