【发布时间】:2015-08-17 13:46:54
【问题描述】:
我有下一个 spring rest 控制器来处理我的异常:
@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));
}
我的实体类:
@Entity
public class Device {
@Id
@Column(name="name", nullable = false)
private String Name;
@Column(name = "send_date")
@NotNull
private Date sendDate;
}
我尝试模拟 ConstraintViolationException,所以在我的控制器中我使用下一个代码:
Device d = new Device();
d.setName("sdsdsd");
d.setSendDate(null);
deviceRepository.save(d);
结果我收到下一个异常:
[dispatcherServlet]:? - Servlet.service() 用于 servlet [dispatcherServlet] 在带有路径 [] 的上下文中抛出异常 [Request 处理失败;嵌套异常是 org.springframework.transaction.TransactionSystemException:不能 提交 JPA 事务;嵌套异常是 javax.persistence.RollbackException:提交时出错 交易]有根本原因 javax.validation.ConstraintViolationException:验证失败 类 [com.entity.Device] 在组更新期间 [javax.validation.groups.Default, ] 列表 违反约束:[ ConstraintViolationImpl{interpolatedMessage='不能为空', propertyPath=sendDate, rootBeanClass=class com.entity.Device, messageTemplate='{javax.validation.constraints.NotNull.message}'} ]
从堆栈跟踪中可以看出,我首先收到 TransactionSystemException,因此我的 ExceptionHandler 方法 (hiberAnnotationExceptionHandler) 不会调用。所以我的问题是如何模拟这个异常(ConstraintViolationException)? 提前致谢。
【问题讨论】: