Search code examples
jsfexceptionfaceletsstack-tracecustom-error-pages

Facelets custom error page - customize / wrap the exception message / stack trace


I am using JBoss AS7. I already know how to use my own web.xml error pages for HTTP Errors (e.g. 404, 500, ...) - thats not a problem. But for debugging reasons I need to view the error StackTrace. How can I access the message that is shown by default and embed it in error page?


Solution

  • The concrete exception instance is available as a request attribute with the name as keyed by RequestDispatcher#ERROR_EXCEPTION which has a value of javax.servlet.error.exception.

    Thus, this will give you the exception:

    #{requestScope['javax.servlet.error.exception']}
    

    However, there's no standard facility to print its stack trace in the view. You'd need to homebrew an EL function, something like as JSF utility library OmniFaces already has in flavor of #{of:printStackTrace()}. You can see it in action in the OmniFaces FullAjaxExceptionHandler showcase page:

    <ui:composition ... xmlns:of="http://omnifaces.org/functions">
    ...
    <li>Stack trace: <pre><code>#{of:printStackTrace(requestScope['javax.servlet.error.exception'])}</code></pre></li>
    

    whereby the function implementation look like this:

    /**
     * Print the stack trace of the given exception.
     * @param exception The exception to print the stack trace for.
     * @return The printed stack trace.
     */
    public static String printStackTrace(Throwable exception) {
        if (exception == null) {
            return null;
        }
    
        StringWriter stringWriter = new StringWriter();
        exception.printStackTrace(new PrintWriter(stringWriter, true));
        return stringWriter.toString();
    }
    

    See also: