[JAVA] getStackTraceString

[JAVA] getStackTraceString

public String getStackTraceString(Throwable throwable) {
    if (throwable == null) {
        return “null”;
    }

    StackTraceElement[] elems = throwable.getStackTrace();
    if (elems == null || elems.length == 0) {
        return “null”;
    }

    StringBuilder builder = new StringBuilder();
    builder.append(throwable.getClass().getName() + “: “ + throwable.getMessage());

    int elemCount = elems.length;
    for (int i=0; i<elemCount; i++) {
        if (elems[i] != null) {
            builder.append(“\n\tat “ + elems[i].toString());
        }
    }

    return builder.toString();
}

Exception 을 catch할 때 보통 e.printStackTrace(); 식으로 쓰는데, 해당 내용을 스트링으로 리턴받고 싶으면 이 메서드를 사용하면 된다.

아래 스크린샷은 e.printStackTrace(); 를 쓰지 않고 System.err.println(getStackTraceString(e)); 를 사용했을 때 콘솔이다. 보다시피 printStackTrace() 와 똑같이 표시된다.

jsp에서는 아래와 같이 쓰면 된다.

<%!
public String getStackTraceString(Throwable throwable) {
    if (throwable == null) {
        return “null”;
    }

    StackTraceElement[] elems = throwable.getStackTrace();
    if (elems == null || elems.length == 0) {
        return “null”;
    }

    StringBuilder builder = new StringBuilder();
    builder.append(throwable.getClass().getName() + “: “ + throwable.getMessage());

    int elemCount = elems.length;
    for (int i=0; i<elemCount; i++) {
        if (elems[i] != null) {
            builder.append(“<br>\tat “ + elems[i].toString());
        }
    }

    return builder.toString();
}
%>