Example usage for javax.servlet RequestDispatcher ERROR_EXCEPTION_TYPE

List of usage examples for javax.servlet RequestDispatcher ERROR_EXCEPTION_TYPE

Introduction

In this page you can find the example usage for javax.servlet RequestDispatcher ERROR_EXCEPTION_TYPE.

Prototype

String ERROR_EXCEPTION_TYPE

To view the source code for javax.servlet RequestDispatcher ERROR_EXCEPTION_TYPE.

Click Source Link

Document

The name of the request attribute under which the type of the exception object is propagated during an error dispatch

Usage

From source file:ru.mystamps.web.controller.ErrorController.java

@RequestMapping(Url.INTERNAL_ERROR_PAGE)
public void internalError(
        // CheckStyle: ignore LineLength for next 3 lines
        @RequestAttribute(name = RequestDispatcher.ERROR_EXCEPTION_TYPE, required = false) Class<?> exceptionType,
        @RequestAttribute(name = RequestDispatcher.ERROR_EXCEPTION, required = false) Exception exception,
        @RequestAttribute(name = RequestDispatcher.ERROR_REQUEST_URI, required = false) String page) {

    // TODO: log to database (with *.status_code, *.message, *.servlet_name and user details)

    if (page != null && !Url.INTERNAL_ERROR_PAGE.equals(page)) {
        String msg = String.format("Exception '%s' occurred at page %s", getNameOrAsIs(exceptionType), page);
        LOG.error(msg, exception);//from   ww w.  j a va  2  s  . com
    }
}

From source file:org.eclipse.gyrex.http.jetty.internal.app.ApplicationHandlerCollection.java

@Override
public void handle(final String target, final Request baseRequest, final HttpServletRequest request,
        final HttpServletResponse response) throws IOException, ServletException {
    // don't do anything if already processed
    if (response.isCommitted() || baseRequest.isHandled())
        return;/*from   w w  w .j a va 2s. co  m*/

    final Iterator<Handler> handlers = this.handlers.iterator();
    if (!handlers.hasNext())
        return;

    final ThroughputMetric requestsMetric = metrics.getRequestsMetric();
    final long requestStart = requestsMetric.requestStarted();
    try {
        doHandle(target, baseRequest, request, response);
        if (response instanceof Response) {
            final int status = ((Response) response).getStatus();
            if (HttpStatus.isServerError(status)) {
                metrics.getRequestsMetric().requestFailed();
                metrics.error(status, ((Response) response).getReason());
            } else {
                metrics.getRequestsMetric().requestFinished(((Response) response).getContentCount(),
                        System.currentTimeMillis() - requestStart);
            }
        } else {
            metrics.getRequestsMetric().requestFinished(0, System.currentTimeMillis() - requestStart);
        }
    } catch (final EofException | RuntimeIOException | ContinuationThrowable e) {
        metrics.getRequestsMetric().requestFailed();
        throw e;
    } catch (final Exception e) {
        metrics.getRequestsMetric().requestFailed();

        final DispatcherType type = baseRequest.getDispatcherType();
        if (!(DispatcherType.REQUEST.equals(type) || DispatcherType.ASYNC.equals(type))) {
            if (e instanceof IOException)
                throw (IOException) e;
            if (e instanceof RuntimeException)
                throw (RuntimeException) e;
            if (e instanceof ServletException)
                throw (ServletException) e;
        }

        // handle or log exception
        else if (e instanceof RuntimeIOException)
            throw (RuntimeIOException) e;
        else if (e instanceof EofException)
            throw (EofException) e;
        else if ((e instanceof IOException) || (e instanceof UnavailableException)
                || (e instanceof IllegalStateException)) {
            if (Platform.inDebugMode()) {
                LOG.debug("Exception processing request {}: {}", request.getRequestURI(),
                        ExceptionUtils.getMessage(e), e);
                LOG.debug(request.toString());
            }
        } else {
            LOG.error("Exception processing request {}: {}",
                    new Object[] { request.getRequestURI(), ExceptionUtils.getRootCauseMessage(e), e });
            if (Platform.inDebugMode()) {
                LOG.debug(request.toString());
            }
        }

        // send error response if possible
        if (!response.isCommitted()) {
            request.setAttribute(RequestDispatcher.ERROR_EXCEPTION_TYPE, e.getClass());
            request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, e);
            if (e instanceof UnavailableException) {
                final UnavailableException ue = (UnavailableException) e;
                if (ue.isPermanent()) {
                    response.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
                } else {
                    response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, e.getMessage());
                }
            } else if (e instanceof IllegalStateException) {
                response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, e.getMessage());
            } else {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
            }
        } else {
            // give up
            if (JettyDebug.debug) {
                LOG.debug("Response already committed for handling {}", ExceptionUtils.getMessage(e));
            }
        }
    } catch (final Error e) {
        metrics.getRequestsMetric().requestFailed();

        // only handle some errors
        if (!((e instanceof LinkageError) || (e instanceof AssertionError)))
            throw e;

        final DispatcherType type = baseRequest.getDispatcherType();
        if (!(DispatcherType.REQUEST.equals(type) || DispatcherType.ASYNC.equals(type)))
            throw e;

        LOG.error("Error processing request {}: {}",
                new Object[] { request.getRequestURI(), ExceptionUtils.getRootCauseMessage(e), e });
        if (JettyDebug.debug) {
            LOG.debug(request.toString());
        }

        // TODO httpResponse.getHttpConnection().forceClose();
        if (!response.isCommitted()) {
            request.setAttribute(RequestDispatcher.ERROR_EXCEPTION_TYPE, e.getClass());
            request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, e);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        } else {
            if (JettyDebug.debug) {
                LOG.debug("Response already committed for handling {}", ExceptionUtils.getMessage(e));
            }
        }
    }
}

From source file:org.ireland.jnetty.webapp.ErrorPageManager.java

public void sendServletErrorImpl(Throwable e, ServletRequest req, ServletResponse res) throws IOException {
    HttpServletResponse response = (HttpServletResponse) res;
    HttpServletRequest request = (HttpServletRequest) req;
    Throwable rootExn = e;/*from w  ww .j av  a  2  s .co  m*/
    Throwable errorPageExn = null;
    LineMap lineMap = null;

    try {
        response.reset();
    } catch (IllegalStateException e1) {
    }

    if (req.isAsyncStarted()) {
        AsyncContext async = req.getAsyncContext();

        if (async != null)
            async.complete();
    }

    if (response instanceof HttpServletResponseImpl) {
        HttpServletResponseImpl resFacade = (HttpServletResponseImpl) response;
        resFacade.killCache();
        resFacade.setNoCache(true);
    }

    if (rootExn instanceof ClientDisconnectException)
        throw (ClientDisconnectException) rootExn;

    String location = null;

    String title = "500 Servlet Exception";
    boolean isBadRequest = false;
    boolean doStackTrace = true;
    boolean isCompileException = false;
    boolean isServletException = false;
    Throwable compileException = null;
    String lineMessage = null;

    boolean lookupErrorPage = true;

    while (true) {
        if (rootExn instanceof LineMapException)
            lineMap = ((LineMapException) rootExn).getLineMap();

        if (lookupErrorPage) {
            errorPageExn = rootExn;
        }

        if (rootExn instanceof DisplayableException) {
            doStackTrace = false;
            isCompileException = true;
            if (compileException == null)
                compileException = rootExn;
        } else if (rootExn instanceof CompileException) {
            doStackTrace = false;
            isCompileException = true;

            if (compileException == null) // ! isLineCompileException)
                compileException = rootExn;
        } else if (rootExn instanceof LineException) {
            if (lineMessage == null)
                lineMessage = rootExn.getMessage();
        }

        if (rootExn instanceof BadRequestException) {
            isBadRequest = true;
        }

        if (rootExn instanceof OutOfMemoryError) {
            String msg = "TcpSocketLink OutOfMemory";

            ShutdownSystem.shutdownOutOfMemory(msg);
        }

        if (location != null || !lookupErrorPage) {
        } else if (rootExn instanceof LineMapException && rootExn instanceof ServletException
                && !(rootExn instanceof LineCompileException) && rootExn.getCause() != null) {
            // hack to deal with JSP wrapping
        } else if (!isServletException) {
            // SRV.9.9.2 Servlet 2.4
            // location = getErrorPage(rootExn, ServletException.class);
            location = getErrorPage(rootExn);
            isServletException = true;
        } else {
            location = getErrorPage(rootExn);
            lookupErrorPage = false;
        }

        if (location != null)
            lookupErrorPage = false;

        if (isBadRequest)
            break;

        Throwable cause = null;
        if (rootExn instanceof ServletException && !(rootExn instanceof LineCompileException))
            cause = ((ServletException) rootExn).getRootCause();
        else {
            lookupErrorPage = false;
            cause = rootExn.getCause();
        }

        if (cause != null)
            rootExn = cause;
        else {
            break;
        }
    }

    if (location == null && lookupErrorPage) {
        location = getErrorPage(rootExn);
    }

    if (location == null)
        location = getErrorPage(500);

    if (isBadRequest) {
        // server/05a0, server/0532

        if (rootExn instanceof CompileException)
            title = rootExn.getMessage();
        else
            title = String.valueOf(rootExn);

        doStackTrace = false;
        isBadRequest = true;

        if (request instanceof CauchoRequest)
            ((CauchoRequest) request).killKeepalive("bad request: " + rootExn);

        response.resetBuffer();

        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);

        /*
         * if (location == null) log.warn(e.toString());
         */
    } else if (rootExn instanceof UnavailableException) {
        UnavailableException unAvail = (UnavailableException) rootExn;

        if (unAvail.isPermanent()) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            title = "404 Not Found";

            if (location == null)
                location = getErrorPage(HttpServletResponse.SC_NOT_FOUND);
        } else {
            response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
            title = "503 Unavailable";

            if (unAvail.getUnavailableSeconds() > 0)
                response.setIntHeader("Retry-After", unAvail.getUnavailableSeconds());

            if (location == null)
                location = getErrorPage(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        }
    } else {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }

    if (location == null)
        location = _defaultLocation;

    if (log.isTraceEnabled())
        log.trace(e.toString(), e);
    else if (isCompileException) {
        if (isBadRequest)
            log.trace(BadRequestException.class.getSimpleName() + ": " + compileException.getMessage());
        else
            log.trace(compileException.getMessage());
    } else if (!doStackTrace)
        log.trace(rootExn.toString());
    else
        log.trace(e.toString(), e);

    if (location != null) {
        if (errorPageExn == null)
            errorPageExn = rootExn;

        request.setAttribute(JSP_EXCEPTION, errorPageExn);
        request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, errorPageExn);
        request.setAttribute(RequestDispatcher.ERROR_EXCEPTION_TYPE, errorPageExn.getClass());
        if (request instanceof HttpServletRequest)
            request.setAttribute(RequestDispatcher.ERROR_REQUEST_URI,
                    ((HttpServletRequest) request).getRequestURI());

        String servletName = getServletName(request);

        if (servletName != null)
            request.setAttribute(RequestDispatcher.ERROR_SERVLET_NAME, servletName);

        request.setAttribute(RequestDispatcher.ERROR_STATUS_CODE, new Integer(500));
        request.setAttribute(RequestDispatcher.ERROR_MESSAGE, errorPageExn.getMessage());

        try {
            RequestDispatcher disp = null;
            // can't use filters because of error pages due to filters
            // or security.

            WebApp webApp = getWebApp();

            if (webApp != null)
                disp = webApp.getRequestDispatcher(location);
            else if (_host != null)
                disp = _host.getWebAppContainer().getRequestDispatcher(location);

            if (disp != null) {
                ((RequestDispatcherImpl) disp).error(request, response);
                return;
            }
        } catch (Throwable e1) {
            log.info(e1.toString(), e1);
            rootExn = e1;
        }
    }

    response.setContentType("text/html");

    String encoding = CharacterEncoding.getLocalEncoding();

    if (encoding != null)
        response.setCharacterEncoding(encoding);
    else {
        Locale locale = Locale.getDefault();
        if (!"ISO-8859-1".equals(Encoding.getMimeName(locale)))
            response.setLocale(Locale.getDefault());
        else
            response.setCharacterEncoding("utf-8");
    }

    PrintWriter out;

    try {
        out = response.getWriter();
    } catch (IllegalStateException e1) {
        log.trace(e1.toString(), e1);

        out = new PrintWriter(new OutputStreamWriter(response.getOutputStream()));
    }

    if (isDevelopmentModeErrorPage()) {
        out.println("<html>");
        if (!response.isCommitted())
            out.println("<head><title>" + escapeHtml(title) + "</title></head>");
        out.println("<body>");
        out.println("<h1>" + escapeHtml(title) + "</h1>");

        out.println("<code><pre>");

        if (debug && !CurrentTime.isTest())
            doStackTrace = true;

        if (doStackTrace) {
            out.println("<script language='javascript' type='text/javascript'>");
            out.println("function show() { document.getElementById('trace').style.display = ''; }");
            out.println("</script>");
            out.print("<a style=\"text-decoration\" href=\"javascript:show();\">[show]</a> ");
        }

        if (compileException instanceof DisplayableException) {
            // ioc/0000
            // XXX: dispExn.print doesn't normalize user.name
            // dispExn.print(out);
            out.println(escapeHtml(compileException.getMessage()));
        } else if (compileException != null)
            out.println(escapeHtml(compileException.getMessage()));
        else
            out.println(escapeHtml(rootExn.toString()));

        if (doStackTrace) {
            out.println("<span id=\"trace\" style=\"display:none\">");
            printStackTrace(out, lineMessage, e, rootExn, lineMap);
            out.println("</span>");
        }

        /*
         * if (doStackTrace || debug) { printStackTrace(out, lineMessage, e, rootExn, lineMap); }
         */

        out.println("</pre></code>");

        printVersion(out);

        out.println("</body></html>");
    } else { // non-development mode
        out.println("<html>");
        out.println("<title>Server Error</title>");
        out.println("<body>");
        out.println("<h1>Server Error</h1>");
        out.println("<p>The server is temporarily unavailable due to an");
        out.println("internal error.  Please notify the system administrator");
        out.println("of this problem.</p>");

        out.println("<pre><code>");
        out.println("Date: " + QDate.formatISO8601(CurrentTime.getCurrentTime()));

        out.println("</code></pre>");

        printVersion(out);

        out.println("</body></html>");
    }

    String userAgent = request.getHeader("User-Agent");

    if (userAgent != null && userAgent.indexOf("MSIE") >= 0) {
        out.print(MSIE_PADDING);
    }

    out.close();
}