Java捕获和显示SqlExceptionHelper

时间:2019-01-23 09:03:57

标签: java sql oracle hibernate

由于其复杂性,因此使用Hibernate JPA在Oracle DB中执行本机查询, 我想捕获从" ORA-01722: Nombre non valide "类抛出的类似SqlExceptionHelper的异常,但是捕获的是:

  

class javax.persistence.PersistenceException:无法提取   结果集

记录器错误跟踪了我,但没有发现它:

jdbc.spi.SqlExceptionHelper   : ORA-01722: Nombre non valide


BigDecimal customerId = null;
try {
    Query q = entityManager.createNativeQuery(
            "select acc.account_id as customerId from Account ...");
    customerId = (BigDecimal) q.getSingleResult();

} catch (Exception e) {

    logger.info("CLASS : " + e.getClass());
    if (e instanceof PersistenceException) {  // should display ORA-01722: Nombre non valide ?
        logger.info("ERRROR : " + e.getMessage());
        throw new SQLException(e.getMessage());
    }else
    if (e instanceof SQLException) {
        logger.info("ERRROR : " + e.getMessage());
        throw new SQLException(e.getMessage());
    }
    logger.info("NOOOOOOOOOOOOO : " + e.getMessage());
    throw new Exception(e.getMessage());
}

2 个答案:

答案 0 :(得分:0)

SQLException作为参数传递给SQLGrammarException构造函数。

您可以捕获,提取根并显示本机sql错误或直接将其重新抛出:

} catch (SQLGrammarException e) {
    logger.info("CLASS : " + e.getClass());
    throw e.getSQLException();
} catch (Exception e){
   ...
}

答案 1 :(得分:0)

@Entity
@Table(uniqueConstraints = { @UniqueConstraint(columnNames = { "continentName" }) })
public class Continent implements Serializable 

    @NotEmpty(message = "continentName is a required field")
    private String continentName;

在您的控制器中,您可以通过以下方式处理 @NotEmpty:

@ExceptionHandler({ ConstraintViolationException.class })
    public ResponseEntity<String> handleError1(HttpServletRequest req, Exception ex) {

        String msg = null;
        if (ex.getCause().getCause() instanceof ConstraintViolationException) {
            ConstraintViolationException e = (ConstraintViolationException) ex.getCause().getCause();
            Optional<ConstraintViolation<?>> optional = e.getConstraintViolations().stream().findFirst();
            msg = optional.isPresent() ? optional.get().getMessageTemplate() : ex.getMessage();
        }

        return new ResponseEntity<>(msg, HttpStatus.CONFLICT);
    }

这将返回“大洲名称是必填字段”

enter image description here

再次在控制器中,此方法将处理唯一的约束违规。假设您已经输入了一个值“Brucrumus”并尝试再次输入:

@ExceptionHandler({ DataIntegrityViolationException.class })
    public ResponseEntity<String> handleError2(HttpServletRequest req, Exception ex) {

        String msg = ex.getMessage();
        if (ex.getCause().getCause() instanceof SQLException) {
            SQLException e = (SQLException) ex.getCause().getCause();

            if (e.getMessage().contains("Key")) {
                msg = e.getMessage().substring(e.getMessage().indexOf("Key"));
            }
        }

enter image description here