1. Introduction
1.介绍
When dealing with exceptions in Java, we’re frequently logging or simply displaying stack traces. However, sometimes, we don’t want just to print the stack trace, we might need to write the stack trace to a file, to a database or even transmit it over the network.
在Java中处理异常时,我们经常要记录或简单地显示堆栈跟踪。然而,有时候,我们并不希望只是打印堆栈跟踪,我们可能需要将堆栈跟踪写入文件、数据库,甚至通过网络传输。
For these purposes, having the stack trace as a String would be very useful. And unfortunately, Java doesn’t provide a very convenient method to do that directly.
出于这些目的,将堆栈跟踪作为一个String是非常有用的。不幸的是,Java并没有提供一个非常方便的方法来直接做到这一点。
2. Conversion with Core Java
2.用Core Java进行转换
Let’s start with the core library.
让我们从核心库开始。
The function printStackTrace() of the Exception class can take one parameter, either a PrintStream or a PrintWriter. Thus, it is possible, using a StringWriter, to print the stack trace into a String:
Exception类的printStackTrace()函数可以接受一个参数,即PrintStream或PrintWriter。因此,我们可以使用StringWriter,将堆栈跟踪打印成String。
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
Then, calling sw.toString() will return the stack trace as a String.
然后,调用sw.toString()将返回堆栈跟踪作为String。
3. Conversion with Commons-Lang
3.用Commons-Lang转换
While the previous method is the simplest way of converting a stack trace to a String using core Java, it remains a bit cumbersome. Fortunately, Apache Commons-Lang provides a function doing the job.
虽然前面的方法是使用核心Java将堆栈跟踪转换为String的最简单方法,但它仍然有点麻烦。幸运的是,Apache Commons-Lang提供了一个函数来完成这项工作。
Apache Commons-Lang is a very useful library offering a lot of features that are missing in the core classes of the Java API, including classes that can be used to work with the exceptions.
Apache Commons-Lang是一个非常有用的库,提供了很多Java API的核心类中所缺少的功能,包括可以用来处理异常的类。
First, let’s start with the project configuration. When using Maven, we just have to add the following dependency to the pom.xml:
首先,让我们从项目配置开始。使用Maven时,我们只需在pom.xml中添加以下依赖项。
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
Then, in our case, the most interesting class is ExceptionUtils, which provides functions to manipulate the exceptions. Using this class, getting the stack trace as a String from an Exception is pretty straightforward:
然后,在我们的案例中,最有趣的类是ExceptionUtils,它提供了操作异常的函数。使用这个类,从一个Exception中获得堆栈跟踪的String是非常直接的。
String stacktrace = ExceptionUtils.getStackTrace(e);
4. Conclusion
4.结论
Getting the stack trace of an exception as a String isn’t difficult, but it’s far from being intuitive. This article presents two ways of doing it, either using core Java or using Apache Commons-Lang.
以String的形式获取异常的堆栈跟踪并不困难,但远不是那么直观。本文介绍了两种方法,可以使用核心Java或者使用Apache Commons-Lang。
Keep in mind that Java 9 will bring a new StackWalking API which should make things easier.
请记住,Java 9将带来一个新的StackWalking API,这应该会让事情变得更简单。
As always, the code samples can be found here on GitHub.
一如既往,代码样本可以在GitHub上找到这里。