【问题标题】:How to get the MySQLIntegrityConstraintViolationException message in hibernate如何在休眠中获取 MySQLIntegrityConstraintViolationException 消息
【发布时间】:2017-06-27 18:25:18
【问题描述】:

我正在尝试处理异常

这是堆栈跟踪;

org.hibernate.exception.ConstraintViolationException: could not execute statement
    at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:59)
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42) 
    ...
    ...
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry 'testemail@gmail.com' for key 'UK_n7ihswpy07ci568w34q0oi8he'

当我尝试使用 getMessage() 方法获取消息时,得到的消息是来自 ConstraintViolationException 的“无法执行语句”,

但我想要的是得到 来自 MySQLIntegrityConstraintViolationException 的“密钥 'UK_n7ihswpy07ci568w34q0oi8he' 的重复条目 'testemail@gmail.com'”消息。

这是我的捕捉过程

catch(MySQLIntegrityConstraintViolationException e){
    e.printStackTrace();
    message = "MySQLIntegrity,\n Duplicate Entry, \n" + e.getMessage();
}
catch(ConstraintViolationException e){
    e.printStackTrace();
    message = "ConstraintViolation,\n Duplicate Entry, \n" + e.getMessage();
}
catch (Exception e) {
    e.printStackTrace();
    message = "Exception rule,\n" + e.getMessage();
}

【问题讨论】:

    标签: hibernate spring-mvc


    【解决方案1】:

    试试

    catch(ConstraintViolationException e){
        e.printStackTrace();
        message = "ConstraintViolation,\n Duplicate Entry, \n" + e.getCause().getMessage();
    }
    

    由: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:重复条目“testemail@gmail.com”键“UK_n7ihswpy07ci568w34q0oi8he”

    原来的例外


    简单的变体:

    private String getRootCauseMessage(Throwable ex){
        if(ex.getCause() == null){
            return ex.getMessage();
        }
        return getRootCauseMessage(ex.getCause());
    }
    

    Throwable cause = originalException;
    while(cause.getCause() != null) {
        cause = cause.getCause();
    }
    

    但由于它是简单的变体,它们可能会无限递归。您可以添加一些计数器并计算递归调用。如果超过 100 则返回空字符串

    如果您可以访问 apache commons,请使用它。 http://commons.apache.org/proper/commons-lang/apidocs/src-html/org/apache/commons/lang3/exception/ExceptionUtils.html,有 getRootCause 方法可以给你根异常,你可以从一个得到按摩/

    【讨论】:

    • 是的,它提供了我需要的东西。谢谢你。后续问题:所以如果我使用 getCause() 方法,那么我可以得到异常的原因,但是如果有很多异常怎么办,getCause() 会给我所有的异常吗?非常感谢先生。你救了我。
    • 感谢 sbjavateam 先生您提供了非常丰富的答案,这对我很有帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-16
    • 1970-01-01
    • 2017-08-12
    • 2023-03-28
    • 2014-01-10
    • 2020-05-23
    • 1970-01-01
    相关资源
    最近更新 更多