本文介绍了获取链式异常Java的详细消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道我如何能够选择最终异常,其中包含一条详细消息,其中包含许多链接异常的所有详细消息。

I'd like to know how I could I thorw a "final" Exception, containing a detail message with all the detail messages of a number of chained exceptions.

例如假设代码如下:

try {
  try {
    try {
      try {
        //Some error here
      } catch (Exception e) {
        throw new Exception("FIRST EXCEPTION", e);
      }
    } catch (Exception e) {
      throw new Exception("SECOND EXCEPTION", e);
    }
  } catch (Exception e) {
    throw new Exception("THIRD EXCEPTION", e);
  }
} catch (Exception e) {
  String allMessages = //all the messages
  throw new Exception(allMessages, e);
}

我对完整的 stackTrace ,但仅限于我写的邮件。我的意思是,我希望得到这样的结果:

I'm not interested in the full stackTrace, but only in the messages I wrote. I mean, I'd like to have a result like this:

java.lang.Exception: THIRD EXCEPTION + SECOND EXCEPTION + FIRST EXCEPTION


推荐答案

我认为你需要的是:

public static List<String> getExceptionMessageChain(Throwable throwable) {
    List<String> result = new ArrayList<String>();
    while (throwable != null) {
        result.add(throwable.getMessage());
        throwable = throwable.getCause();
    }
    return result; //["THIRD EXCEPTION", "SECOND EXCEPTION", "FIRST EXCEPTION"]
}

这篇关于获取链式异常Java的详细消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-11 08:20