I have next spring rest controller for handle my exception:
@ExceptionHandler(ConstraintViolationException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public @ResponseBody
ExceptionResponseDTO hiberAnnotationExceptionHandler(ConstraintViolationException exception) {
return new ExceptionResponseDTO("Entity is null or we are out of range!", exception.getMessage(), ExceptionMapper.INSTANCE.exceptionToExceptionDTO(exception));
}
My entity class:
@Entity
public class Device {
@Id
@Column(name="name", nullable = false)
private String Name;
@Column(name = "send_date")
@NotNull
private Date sendDate;
}
I try to emulate ConstraintViolationException, so in my controller I use next code:
Device d = new Device();
d.setName("sdsdsd");
d.setSendDate(null);
deviceRepository.save(d);
And as result I receive next exception:
[dispatcherServlet]:? - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.transaction.TransactionSystemException: Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Error while committing the transaction] with root cause javax.validation.ConstraintViolationException: Validation failed for classes [com.entity.Device] during update time for groups [javax.validation.groups.Default, ] List of constraint violations:[ ConstraintViolationImpl{interpolatedMessage='may not be null', propertyPath=sendDate, rootBeanClass=class com.entity.Device, messageTemplate='{javax.validation.constraints.NotNull.message}'} ]
So as you can see from stacktrace I receive TransactionSystemException first and because of this my ExceptionHandler method (hiberAnnotationExceptionHandler) doesn't call. So my question is how to emulate this exception (ConstraintViolationException)? Thanks in advance.