Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting user-friendly exception details in Java

I've got a J2EE web application that I'm working on and when an exception occurs, I'd like to get some basic details about the exception and log it. The message that I'm logging should be pretty basic, something that might mean something to the people running the web server(s).

Would using e.getMessage() be the best thing to log? Thanks.

like image 751
Jon Onstott Avatar asked Apr 15 '26 00:04

Jon Onstott


1 Answers

Possibly. Problem is that without at least the calling method info, this isn't terribly helpful

Consider something like the following

/**
 * Returns <i>class.method:linenumber</i> of the caller (or, more accurately
 * the caller of the caller).
 * </p>
 *
 * <p>
 * Returns unknown if stacktrace is mucked up. Uses reflection and string
 * concatenation, so don't overuse this for trivial matters. For exception
 * handling and for logging, on the other hand, it is useful.
 *
 * @return method name of caller's caller and line number (String)
 */
public static String returnCaller( Class ignoreMe )
{

    String              ignoreClass = ignoreMe.getName();
    StackTraceElement[] steArr      = new Throwable().getStackTrace();

    if (steArr != null)
    {
        // subscript 1 is returnCaller().
        // subscript 2 is the caller of returnCaller()
        // subscript 3 is the caller of the caller of returnCaller()...
        for( int i = 0; i < steArr.length; i++)
        {
            if (steArr[i] == null)
                break;

            String myclass = steArr[i].getClassName();

            if (myclass.equals(ErrorHandle.class.getName()))
                continue;

            if (ignoreClass.equals(myclass))
                continue;

            return steArr[i].getClassName()
                    + "."
                    + steArr[i].getMethodName()
                    + ":"
                    + steArr[i].getLineNumber();
        }
    }

    return "unknown";
}
like image 107
MJB Avatar answered Apr 16 '26 13:04

MJB