gpt4 book ai didi

Java 捕获并显示 SqlExceptionHelper

转载 作者:太空宇宙 更新时间:2023-11-04 09:54:35 24 4
gpt4 key购买 nike

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

class javax.persistence.PersistenceException: could not extract ResultSet

记录器错误跟踪我但没有捕获:

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());
}

最佳答案

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

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

在您的 Controller 中,您可以使用以下方法处理@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

同样在 Controller 中,此方法将处理唯一约束违规。假设您已经输入了值“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

关于Java 捕获并显示 SqlExceptionHelper,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54323487/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com