java 如何循环通过Exception getCause()查找根本原因并显示详细消息[duplicate]

9udxz4iz  于 2023-02-20  发布在  Java
关注(0)|答案(9)|浏览(197)
    • 此问题在此处已有答案**:

Java - find the first cause of an exception(12个答案)
三年前关闭了。
我试图在休眠中调用saveOrUpdate()来保存数据。由于列有唯一索引,所以当我通过Eclipse调试器查看时,它会抛出ConstraintViolationException
因为在将数据插入表时,不同异常的根本原因可能不同。
我想知道,如何循环/遍历getCause()以检查异常的根本原因及其消息。
更新:
感谢大家的友好回应,事情是我想在下面的图像输出一样:

我需要访问detailMessage字段。
(我真的很抱歉,如果我不能把我的问题说得更清楚。)
谢谢。

zyfwsgd6

zyfwsgd61#

Apache ExceptionUtils提供了以下方法:

Throwable getRootCause(Throwable throwable)

以及

String getRootCauseMessage(Throwable th)
bmp9r5qi

bmp9r5qi2#

我通常使用下面的实现,而不是Apache的实现。
除了复杂性之外,Apache的实现在找不到原因时返回null,这迫使我对null执行额外的检查。
通常,当寻找异常的根本原因时,我已经有了一个非空异常作为开始,如果找不到更深层次的原因,那么所有预期的建议都是失败的原因。

Throwable getCause(Throwable e) {
    Throwable cause = null; 
    Throwable result = e;

    while(null != (cause = result.getCause())  && (result != cause) ) {
        result = cause;
    }
    return result;
}
kzmpq1sx

kzmpq1sx3#

使用java 8 Stream API,这可以通过以下方式实现:

Optional<Throwable> rootCause = Stream.iterate(exception, Throwable::getCause)
                                      .filter(element -> element.getCause() == null)
                                      .findFirst();

注意,这段代码不能避免异常原因循环,因此在生产中应该避免。

dly7yett

dly7yett4#

你想要这样的东西吗?

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

还是我漏掉了什么

3yhwsihp

3yhwsihp5#

Guava's Throwables提供以下方法:

Throwable getRootCause(Throwable throwable)

以及

String getStackTraceAsString(Throwable throwable)
shstlldc

shstlldc6#

APACHE中;实现方式如下。
突出显示的是list。contains(throwable)== false

public static Throwable getRootCause(final Throwable throwable) {
    final List<Throwable> list = getThrowableList(throwable);
    return list.size() < 2 ? null : (Throwable)list.get(list.size() - 1);
}

public static List<Throwable> getThrowableList(Throwable throwable) {
    final List<Throwable> list = new ArrayList<Throwable>();
    while (throwable != null && list.contains(throwable) == false) {
        list.add(throwable);
        throwable = ExceptionUtils.getCause(throwable);
    }
    return list;
}
xwbd5t1u

xwbd5t1u7#

} catch (Exception ex) {
    while (ex.getCause() != null)
        ex = ex.getCause();
    System.out.println("Root cause is " + ex.getMessage());
}

你以为会有更复杂的事吗?

vuv7lop3

vuv7lop38#

试试这个,你可以把这个函数放在一个Util类中:

public static Throwable getRootException(Throwable exception){
 Throwable rootException=exception;
 while(rootException.getCause()!=null){
  rootException = rootException.getCause();
 }
 return rootException;
}

用法示例:

catch(MyException e){
  System.out.println(getRootException(e).getLocalizedMessage());
}

来源:How to get the root exception of any exception

ruoxqz4g

ruoxqz4g9#

递归:

public static Throwable getRootCause(Throwable e) {
    if (e.getCause() == null) return e;
    return getRootCause(e.getCause());
}

相关问题