为了账号安全,请及时绑定邮箱和手机立即绑定

在默认为任何运行时错误的异常处理程序之前,如何让@ExceptionHandlers 处理特定异常?

在默认为任何运行时错误的异常处理程序之前,如何让@ExceptionHandlers 处理特定异常?

守着一只汪 2022-10-20 15:13:02
我想使用 @ExceptionHandler 来处理任何 Hibernate 异常。如果异常不是 Hibernate 异常,则运行时错误的 @ExceptionHandler 会处理异常。问题是,运行时异常总是优先于 Hibernate 异常处理程序。意思是,发生的任何休眠异常都由通用运行时异常处理程序处理。如何确保 Hibernate 异常由其异常处理程序处理,而不是由运行时异常处理?    '@ExceptionHandler(HibernateException.class)public String handleHibernateException(HibernateException exc, Model theModel) {    String message = "An error has occured: " + exc.getLocalizedMessage() + "\n" + exc.getCause().toString()            + "\r\n";    myLogger.warning(message);    theModel.addAttribute("exception", message);    return "testing";}// handle any other runtime/unchecked exception and log it@ExceptionHandler(RuntimeException.class)public String handleRuntimeExceptions(RuntimeException exc, Model theModel) {    String message = "An error has occured: " + exc.getLocalizedMessage() + "\n" + exc.getCause().toString()            + "\r\n";    myLogger.warning(message);    theModel.addAttribute("exception", message);    return "testing";}'
查看完整描述

1 回答

?
一只萌萌小番薯

TA贡献1795条经验 获得超7个赞

您可以通过以下方式检查异常是否是 HibernateException 的实例:


@ExceptionHandler(RuntimeException.class)

public String handleRuntimeExceptions(RuntimeException exc, Model theModel) {

    if (exc instanceof HibernateException) {

        return handleHibernateException((HibernateException) exc.getCause(), theModel);

    } else if (exc.getCause() instanceof HibernateException) {

        HibernateException hibernateException = (HibernateException) exc.getCause();

        return handleHibernateException(hibernateException, theModel);

    }

    String message = "An error has occurred: " + exc.getLocalizedMessage() + "\n" + exc.getCause().toString() + "\r\n";

    myLogger.warning(message);

    theModel.addAttribute("exception", message);

    return "testing";

}


查看完整回答
反对 回复 2022-10-20
  • 1 回答
  • 0 关注
  • 87 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号