将Throwable.getStackTrace()的结果转换为描述堆栈跟踪的字符串最简单的方法是什么?
当前回答
我想知道为什么没有人提到ExceptionUtils.getStackFrames(exception)
对我来说,这是将堆栈跟踪及其所有原因转储到底的最方便方法:
String.join("\n", ExceptionUtils.getStackFrames(exception));
其他回答
以下代码允许您使用字符串格式获取整个stackTrace,而无需使用log4J或java.util.Logger等API:
catch (Exception e) {
StackTraceElement[] stack = e.getStackTrace();
String exception = "";
for (StackTraceElement s : stack) {
exception = exception + s.toString() + "\n\t\t";
}
System.out.println(exception);
// then you can send the exception string to a external file.
}
警告:这可能有点离题,但哦,好吧…;)
我不知道最初的海报是什么原因让堆栈跟踪成为字符串。当堆栈跟踪应该以SLF4J/Logback LOG结尾,但没有或应该抛出异常时,我会这样做:
public void remove(List<String> ids) {
if(ids == null || ids.isEmpty()) {
LOG.warn(
"An empty list (or null) was passed to {}.remove(List). " +
"Clearly, this call is unneccessary, the caller should " +
"avoid making it. A stacktrace follows.",
getClass().getName(),
new Throwable ("Stacktrace")
);
return;
}
// actual work, remove stuff
}
我喜欢它,因为它不需要外部库(当然,除了您的日志后端,它大部分时间都会在那里)。
我想知道为什么没有人提到ExceptionUtils.getStackFrames(exception)
对我来说,这是将堆栈跟踪及其所有原因转储到底的最方便方法:
String.join("\n", ExceptionUtils.getStackFrames(exception));
解决方案是将数组的stackTrace转换为字符串数据类型。请参见以下示例:
import java.util.Arrays;
try{
}catch(Exception ex){
String stack = Arrays.toString(ex.getStackTrace());
System.out.println("stack "+ stack);
}
这应该是有效的:
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String exceptionAsString = sw.toString();
推荐文章
- 在流中使用Java 8 foreach循环移动到下一项
- 访问限制:'Application'类型不是API(必需库rt.jar的限制)
- 用Java计算两个日期之间的天数
- 如何配置slf4j-simple
- 在Jar文件中运行类
- 带参数的可运行?
- 我如何得到一个字符串的前n个字符而不检查大小或出界?
- 我可以在Java中设置enum起始值吗?
- Java中的回调函数
- c#和Java中的泛型有什么不同?和模板在c++ ?
- 在Java中,流相对于循环的优势是什么?
- Jersey在未找到InjectionManagerFactory时停止工作
- 在Java流是peek真的只是调试?
- Recyclerview不调用onCreateViewHolder
- 将JSON字符串转换为HashMap