Spring boot 如何处理JPA函数异常
当我调用JPA的save()时,它给出了ConstraintViolation异常的异常,但它在嵌套异常中 首先是非法状态异常,然后是NestedServletException、DataIntegrotyViolationException、ConstraintViolationException、SQLServerException 那里 在CustomExceptionHandler类中,我添加了Spring boot 如何处理JPA函数异常,spring-boot,jpa,spring-data-jpa,jpa-2.0,jpa-2.1,Spring Boot,Jpa,Spring Data Jpa,Jpa 2.0,Jpa 2.1,当我调用JPA的save()时,它给出了ConstraintViolation异常的异常,但它在嵌套异常中 首先是非法状态异常,然后是NestedServletException、DataIntegrotyViolationException、ConstraintViolationException、SQLServerException 那里 在CustomExceptionHandler类中,我添加了 @ExceptionHandler({ GenericJDBCException.class
@ExceptionHandler({ GenericJDBCException.class, SQLException.class, DuplicateKeyException.class,
ConstraintViolationException.class, JDBCException.class })
public ResponseEntity<Object> processSqlExceptions(SQLException e, WebRequest request) {
logger.error("SQL Error : ", e);
logger.warn("SQL Error : ", e);
ErrorResponse error = new ErrorResponse("600", e.getMessage(), tracer.currentSpan().context().spanIdString());
return handleExceptionInternal(e, error, new HttpHeaders(), HttpStatus.BAD_REQUEST, request);
}
@ExceptionHandler({genericjdbception.class,SQLException.class,DuplicateKeyException.class,
ConstraintViolationException.class,JDBCException.class})
公共响应属性处理SQLException(SQLException e、WebRequest请求){
logger.error(“SQL错误:”,e);
logger.warn(“SQL错误:”,e);
ErrorResponse error=新的ErrorResponse(“600”,例如getMessage(),tracer.currentSpan().context().spanIdString());
返回handleExceptionInternal(e,错误,新建HttpHeaders(),HttpStatus.BAD_请求,请求);
}
我试图处理一些异常,但它仍然无法处理异常。它是一个
DataIntegrityViolationException
,因此您应该将它添加到处理程序中
@ExceptionHandler(value = {DataIntegrityViolationException.class})
如果使用
hibernate
,则它会抛出自己版本的ConstraintViolationException
因此,请确保您处理的是
org.hibernate.exception.ConstraintViolationException
,而不是javax.validation.ConstraintViolationException
(或两者兼而有之).在转到数据库之前,您应该验证数据,并在验证错误时返回有意义的消息。您是否尝试过在ExceptionHandler中添加SQLServerException?
@ExceptionHandler(value = {DataIntegrityViolationException.class})