001package org.kohsuke.stapler.compression;
002
003import org.kohsuke.stapler.AttributeKey;
004
005import javax.servlet.ServletContext;
006import javax.servlet.ServletException;
007import javax.servlet.http.HttpServletRequest;
008import javax.servlet.http.HttpServletResponse;
009import java.io.IOException;
010import java.io.PrintWriter;
011import java.io.StringWriter;
012import java.text.MessageFormat;
013import java.util.Date;
014
015import static org.kohsuke.stapler.Stapler.escape;
016
017/**
018 * Handles an exception caught by {@link CompressionFilter}.
019 *
020 * See {@link CompressionFilter} javadoc for why this exception needs to be handled
021 * by us and can't just be handled by the servlet container like it does all others.
022 *
023 * @author Kohsuke Kawaguchi
024 */
025public interface UncaughtExceptionHandler {
026    /**
027     * Called to render the exception as an HTTP response.
028     */
029    void reportException(Throwable e, ServletContext context, HttpServletRequest req, HttpServletResponse rsp)
030            throws ServletException, IOException;
031
032
033    UncaughtExceptionHandler DEFAULT = new UncaughtExceptionHandler() {
034        public void reportException(Throwable e, ServletContext context, HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException {
035            StringWriter sw = new StringWriter();
036            PrintWriter pw = new PrintWriter(sw);
037            e.printStackTrace(pw);
038            pw.close();
039
040            rsp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
041            rsp.setContentType("text/html");
042            PrintWriter w = rsp.getWriter();
043            String message = e.getMessage();
044            w.print(MessageFormat.format("<html><head><title>Error {0}</title></head>\n" +
045                    "<body bgcolor=#fff><h1>Status Code: {0}</h1>Exception: {1}<br>Stacktrace: <pre>{2}</pre><br><hr>\n" +
046                    "<i>Generated by Stapler at {3}</i></body></html>",
047                    HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
048                    message != null ? escape(message) : "?",
049                    escape(sw.toString()),
050                    new Date().toString()
051            ));
052            w.close();
053        }
054    };
055}