Issue
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...
Solution
There're 3 ways:
@Valid
\@Validated
annotations.Once they used at parameter level, violations are available via method-injected
Errors
\BindingResult
type implementations.ConstraintViolationException
is thrown each time an entity in non-valid state is passed to.save()
or.persist()
Hibernate methods.Entities may be manually validated via injected
LocalValidatorFactoryBean.validate()
method. The constraint violations then available through passedErrors
object's implementation. Exactly, how@Valid
\@Validated
annotations are internally implemented.
Answered By - WildDev