【发布时间】:2020-01-19 11:37:08
【问题描述】:
当我调用 JPA 的 save() 时,它给出了 ConstraintViolation 异常,但它在嵌套异常中。
第一个是 IllegalStateException,然后是 NestedServletException、DataIntegrotyViolationException、ConstraintViolationException、SQLServerException 那里
com.microsoft.sqlserver.jdbc.SQLServerException: Violation of UNIQUE KEY constraint 'uk_urmapping_uname_role'. Cannot insert duplicate key in object 'dbo.employee_role_mapping'. The duplicate key value is (wxy ., ABC).
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:259) ~[mssql-jdbc-6.4.0.jre8.jar:na]
at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1547) ~[mssql-jdbc-6.4.0.jre8.jar:na]
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:548) ~[mssql-jdbc-6.4.0.jre8.jar:na]
在我添加的 CustomExceptionHandler 类中
@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中添加SQLServerException吗?
标签: spring-boot jpa spring-data-jpa jpa-2.0 jpa-2.1