开发者

How to display stack trace on a caught exception?

开发者 https://www.devze.com 2022-12-19 17:55 出处:网络
I have a generic function that prints exceptions (using log4j): private void _showErrorMessage(Exception e) {

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:

  • log4j can do it
  • commons logging can do it
  • java.util.logging can do it

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);
}


I use the ExceptionUtils#getFullStackTrace method of Jakarta Commons Lang


Throwable.getStackTrace returns an array of StackTraceElements, 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.


You could also look at the Guava libraries from Google.

Throwables.getStackTraceAsString(Throwable throwable)


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.


Exception Stacktrace logging shows two methods for this purpose, one based on Apache Commons and another using the standard JDK method.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号