简体   繁体   中英

How to display stack trace on a caught exception?

I have a generic function that prints exceptions (using log4j):

private void _showErrorMessage(Exception e) {
    log.error(e.getClass() + ": " +  e.getMessage() + ": " + e.getCause() + "\n" +  e.getStackTrace().toString());
}

Instead of seeing the stack trace I'm seeing:

[Ljava.lang.StackTraceElement;@49af7e68

How can I view the stack trace of the exception properly?

update

log.error(e) <- shows the error, but doesn't show stack trace

Your logging framework should have the ability to log exceptions, so simply passing the exception to the proper .error(Object, Throwable) call should be enough:

If your logging framework can't do that, or you need the stack trace in a String for any other reason, then it becomes a bit harder. You'll have to create a PrintWriter wrapping a StringWriter and call .printStackTrace() on the Exception :

StringWriter sw = new StringWriter();
ex.printStackTrace(new PrintWriter(sw));
String stacktrace = sw.toString();

Have you tried?

private void _showErrorMessage(Exception e) {
    log.error("Hey! got an exception", e);
}

Throwable.getStackTrace returns an array of StackTraceElement s, hence the toString method is returning a textual representation of the array itself.

In order to actually retrieve the stack trace information, one would have to go through each StackTraceElement to get more information.

您还可以查看 Google 的 Guava 库。

Throwables.getStackTraceAsString(Throwable throwable)

异常堆栈跟踪日志显示了两种用于此目的的方法,一种基于 Apache Commons,另一种使用标准 JDK 方法。

The exact answer to your question is that you should call Log4J like this:

private void _showErrorMessage(Exception e) {
    log.error(e.getClass() + ": " +  e.getMessage() + ": " + e.getCause(), e);
}

Although I would dispense with the call to e.getCause() because the stacktrace will give that to you anyway, so:

private void _showErrorMessage(Exception e) {
    log.error(e.getClass() + ": " +  e.getMessage(), e);
}

ExceptionUtils is fine if you really need a string of the stacktrace, but since you are using Log4J, you lose a lot by not utilizing its built in exception handling.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM