【问题标题】:How to handle JPA function exception如何处理 JPA 函数异常
【发布时间】:2020-01-19 11:37:08
【问题描述】:

当我调用 JPA 的 save() 时,它给出了 ConstraintViolation 异常,但它在嵌套异常中。

第一个是 IllegalStateException,然后是 NestedServletExceptionDataIntegrotyViolationExceptionConstraintViolationExceptionSQLServerException 那里

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


【解决方案1】:

这是一个DataIntegrityViolationException,所以您应该将它添加到处理程序中。

@ExceptionHandler(value = {DataIntegrityViolationException.class})

【讨论】:

    【解决方案2】:

    如果你使用hibernate,那么它会抛出它自己的ConstraintViolationException 版本。

    因此,请确保您处理的是 org.hibernate.exception.ConstraintViolationException 而不是 javax.validation.ConstraintViolationException(或两者都处理)。

    【讨论】:

      猜你喜欢
      • 2015-05-28
      • 1970-01-01
      • 2017-04-14
      • 2013-04-15
      • 1970-01-01
      • 1970-01-01
      • 2020-08-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多