gpt4 book ai didi

java - @ExceptionHandler 不适用于特定的 hibernate 异常

转载 作者:行者123 更新时间:2023-11-30 10:15:59 27 4
gpt4 key购买 nike

我正在 try catch 一些内部 异常,然后用更好的消息提示最终用户。但是当涉及到这个异常时:

Exception StackTrace

08/May/2018:20:39:09.947 +0800 ERROR o.h.e.j.spi.SqlExceptionHelper [] ERROR: update or delete on table "alert_rule" violates foreign key constraint "alert_alert_rule_id_fkey" on table "alert"
Detail: Key (id)=(58) is still referenced from table "alert".
08/May/2018:20:39:09.977 +0800 ERROR o.a.c.c.C.[.[.[.[dispatcherServlet] [] Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [alert_alert_rule_id_fkey]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause
org.postgresql.util.PSQLException: ERROR: update or delete on table "alert_rule" violates foreign key constraint "alert_alert_rule_id_fkey" on table "alert"
Detail: Key (id)=(58) is still referenced from table "alert".

@ExceptionHandler(value = {javax.validation.ConstraintViolationException.class,
org.hibernate.exception.ConstraintViolationException.class})
似乎没有按预期工作。

我刚刚检查了这个post它指出当与 general 处理程序一起使用时,应该处理 specific 异常处理程序。

还有这个post ,因此可以在一个 处理程序中处理多个 异常。

@RestControllerAdvice
@Slf4j
public class GlobalControllerExceptionHandler {

@ExceptionHandler(value = {javax.validation.ConstraintViolationException.class,
org.hibernate.exception.ConstraintViolationException.class})
public void constraintViolationException(Exception ex,
WebRequest req) {
log.error("Constraint violation while processing {}", req.toString());
}



@ExceptionHandler(value = {Exception.class})
public void unknownException(Exception ex, WebRequest req) {
log.error("Unknown Internal Exception happens");
}
}

我是否遗漏了什么,感谢您提供任何有用的详细信息。

最佳答案

您正在尝试处理 DataIntegrityViolationException,但您的异常处理程序仅处理 ConstraintViolationException

将异常类型添加到处理程序:

@ExceptionHandler({
javax.validation.ConstraintViolationException.class,
org.hibernate.exception.ConstraintViolationException.class,
org.springframework.dao.DataIntegrityViolationException})

关于java - @ExceptionHandler 不适用于特定的 hibernate 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50231845/

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