How can I convert a stack trace to a string?

前端 未结 30 1167
再見小時候
再見小時候 2020-11-22 14:51

What is the easiest way to convert the result of Throwable.getStackTrace() to a string that depicts the stacktrace?

30条回答
  •  抹茶落季
    2020-11-22 15:13

    Warning: This may be a bit off topic, but oh well... ;)

    I don't know what the original posters reason was for wanting the stack trace as string in the first place. When the stack trace should end up in an SLF4J/Logback LOG, but no exception was or should be thrown here's what I do:

    public void remove(List 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
    }
    

    I like it because it does not require an external library (other than your logging backend, which will be in place most of the time anyway, of course).

提交回复
热议问题