get Most Specific Cause Message Info - Java java.lang

Java examples for java.lang:Throwable

Description

get Most Specific Cause Message Info

Demo Code


//package com.java2s;

public class Main {

    public static final String LINE_SEPARATOR = System
            .getProperty("line.separator");

    public static String getMostSpecificCauseMessageInfo(Throwable ex) {
        //get rootCause of exception
        Throwable rootCause = getMostSpecificCause(ex); //?   
        StackTraceElement[] elements = rootCause.getStackTrace(); //Stack trace?elements

        String rootException = rootCause.getClass().getName();
        String rootExceptionMsg = rootCause.getLocalizedMessage();

        String rootCauseSpotClass = elements[0].getClassName(); //?
        String rootCauseSpotMethod = elements[0].getMethodName(); //
        int rootCauseSpotLine = elements[0].getLineNumber(); //

        StringBuilder sbdr = new StringBuilder(LINE_SEPARATOR);

        sbdr.append("[Root Exception]: ").append(rootException)
                .append(LINE_SEPARATOR)/*from   www .j a  v  a 2  s  . c o m*/
                .append("[Root Exception Message]: ")
                .append(rootExceptionMsg).append(LINE_SEPARATOR)
                .append("[Root Exception throwed on]: ")
                .append(rootCauseSpotClass).append(".")
                .append(rootCauseSpotMethod).append("  Line:")
                .append(rootCauseSpotLine);

        return sbdr.toString();
    }

    public static Throwable getMostSpecificCause(Throwable ex) {
        Throwable rootCause = getRootCause(ex);
        return (rootCause != null ? rootCause : ex);
    }

    public static Throwable getRootCause(Throwable ex) {
        Throwable rootCause = null;
        Throwable cause = ex.getCause();
        while (cause != null && cause != rootCause) {
            rootCause = cause;
            cause = cause.getCause();
        }
        return rootCause;
    }
}

Related Tutorials