List of usage examples for javax.servlet RequestDispatcher ERROR_EXCEPTION
String ERROR_EXCEPTION
To view the source code for javax.servlet RequestDispatcher ERROR_EXCEPTION.
Click Source Link
From source file:com.cloudera.oryx.lambda.serving.ErrorResourceTest.java
@Test public void testError() { MockHttpServletRequest mockRequest = new MockHttpServletRequest(); mockRequest.setAttribute(RequestDispatcher.ERROR_STATUS_CODE, 500); mockRequest.setAttribute(RequestDispatcher.ERROR_REQUEST_URI, "http://foo/bar"); mockRequest.setAttribute(RequestDispatcher.ERROR_MESSAGE, "Something was wrong"); mockRequest.setAttribute(RequestDispatcher.ERROR_EXCEPTION, new IllegalStateException()); testResponse(new ErrorResource().errorHTML(mockRequest), false); testResponse(new ErrorResource().errorText(mockRequest), false); testResponse(new ErrorResource().errorEmpty(mockRequest), true); }
From source file:com.hp.autonomy.frontend.find.core.web.AbstractErrorControllerTest.java
@Test public void serverErrorPageWithUUID() { request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, mock(Exception.class)); assertNotNull(errorController.serverErrorPage(request, response)); verify(controllerUtils)//w w w .j av a2 s . com .buildErrorModelAndView(argThat(new HasPropertyWithValue<ErrorModelAndViewInfo>("mainMessageCode", is(CustomErrorController.MESSAGE_CODE_INTERNAL_SERVER_ERROR_MAIN)))); verify(controllerUtils) .buildErrorModelAndView(argThat(new HasPropertyWithValue<ErrorModelAndViewInfo>("subMessageCode", is(CustomErrorController.MESSAGE_CODE_INTERNAL_SERVER_ERROR_SUB)))); }
From source file:com.hp.autonomy.frontend.find.core.web.CustomErrorController.java
@RequestMapping(DispatcherServletConfiguration.SERVER_ERROR_PATH) public ModelAndView serverErrorPage(final HttpServletRequest request, final HttpServletResponse response) { final Exception exception = (Exception) request.getAttribute(RequestDispatcher.ERROR_EXCEPTION); return controllerUtils.buildErrorModelAndView(new ErrorModelAndViewInfo.Builder().setRequest(request) .setMainMessageCode(MESSAGE_CODE_INTERNAL_SERVER_ERROR_MAIN) .setSubMessageCode(MESSAGE_CODE_INTERNAL_SERVER_ERROR_SUB).setSubMessageArguments(null) .setStatusCode(response.getStatus()).setContactSupport(true).setButtonHref(getErrorUrl(request)) .setException(exception).build()); }
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);/* www . ja v a 2 s.c o m*/ } }
From source file:org.tec.webapp.web.ErrorServlet.java
/** * process the error/* www . j a v a 2s . c o m*/ * @param request the request instance * @param response the response instance * @throws IOException if processing fails */ protected void processError(HttpServletRequest request, HttpServletResponse response) throws IOException { Throwable throwable = (Throwable) request.getAttribute(RequestDispatcher.ERROR_EXCEPTION); Integer statusCode = (Integer) request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE); String requestUri = (String) request.getAttribute(RequestDispatcher.ERROR_REQUEST_URI); LOGGER.error("failed to process " + requestUri + " error code: " + statusCode); WebError we; if (throwable != null) { LOGGER.error("error", throwable); we = new WebError(throwable.getMessage(), ErrorCodes.UNRESOLVEABLE_ERROR); } else { we = new WebError("error", ErrorCodes.UNRESOLVEABLE_ERROR); } PrintWriter pw = null; try { response.setStatus(statusCode != null ? statusCode : HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.setContentType(MimeTypeUtils.APPLICATION_JSON_VALUE); pw = response.getWriter(); pw.write(we.toJSON()); pw.flush(); } finally { if (pw != null) { pw.close(); } } }
From source file:fr.gael.dhus.server.http.valve.AccessValve.java
@Override public void invoke(Request request, Response response) throws IOException, ServletException { // valve disabled or previous valve sent an error, return if (!isEnable() || response.isError()) { getNext().invoke(request, response); return;//from w w w . j av a 2s.com } final AccessInformation ai = new AccessInformation(); ai.setConnectionStatus(new PendingConnectionStatus()); // To be sure not to retrieve the same date trough concurrency calls. synchronized (this) { ai.setStartTimestamp(System.nanoTime()); ai.setStartDate(new Date()); } try { this.doLog(request, response, ai); } finally { Element cached_element = new Element(UUID.randomUUID(), ai); getCache().put(cached_element); try { // Log of the pending request command. if (isUseLogger()) LOGGER.info("Access " + ai); getNext().invoke(request, response); } catch (Throwable e) { response.addHeader("cause-message", e.getClass().getSimpleName() + " : " + e.getMessage()); //ai.setConnectionStatus(new FailureConnectionStatus(e)); response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); //throw e; } finally { ai.setReponseSize(response.getContentLength()); ai.setWrittenResponseSize(response.getContentWritten()); if (response.getStatus() >= 400) { String message = RequestUtil.filter(response.getMessage()); if (message == null) { // The cause-message has been inserted into the reponse header // at error handler time. It no message is retrieved in the // standard response, the cause-message is used. message = response.getHeader("cause-message"); } Throwable throwable = null; if (message != null) throwable = new Throwable(message); else throwable = (Throwable) request.getAttribute(RequestDispatcher.ERROR_EXCEPTION); if (throwable == null) throwable = new Throwable(); ai.setConnectionStatus(new FailureConnectionStatus(throwable)); } else ai.setConnectionStatus(new SuccessConnectionStatus()); ai.setEndTimestamp(System.nanoTime()); if ((getPattern() == null) || ai.getRequest().matches(getPattern())) { cached_element.updateUpdateStatistics(); if (isUseLogger()) LOGGER.info("Access " + ai); } } } }
From source file:de.metas.ui.web.config.WebuiExceptionHandler.java
@Override public Throwable getError(final RequestAttributes requestAttributes) { Throwable exception = getAttribute(requestAttributes, REQUEST_ATTR_EXCEPTION); if (exception == null) { exception = getAttribute(requestAttributes, RequestDispatcher.ERROR_EXCEPTION); }/*from w ww.ja v a2s.c o m*/ return exception; }
From source file:org.apache.catalina.core.StandardContextValve.java
/** * Select the appropriate child Wrapper to process this request, based on * the specified request URI. If no matching Wrapper can be found, return an * appropriate HTTP error./* w ww .j a va2 s . c o m*/ * * @param request * Request to be processed * @param response * Response to be produced * * @exception IOException * if an input/output error occurred * @exception ServletException * if a servlet error occurred */ @Override public final void invoke(Request request, Response response) throws IOException, ServletException { StringBuffer sb = new StringBuffer(); Map map = request.getParameterMap(); Set<String> keySet = map.keySet(); for (String key : keySet) { String[] values = (String[]) map.get(key); for (String value : values) { sb.append("&" + key + "=" + value); } } String param = ""; if (0 != sb.length()) param = "?" + sb.toString().substring(1, sb.toString().length()); StandardContext context = (StandardContext) this.getContainer(); StandardHost host = (StandardHost) context.getParent(); int port = CatalinaUtil.getPort(host); List<Tomcat> ts = MapperUtil.tomcatMapper.list(); for (Tomcat t : ts) { if (t.getPort() == port) { List<WebApp> ws = MapperUtil.webAppMapper.listByTomcat(t); for (WebApp w : ws) { if (w.nameMatch(context)) { LastVisitManager.put(w.getId(), request.getRequestURI() + param); } } } } // StandardHost host = (StandardHost) this.getContainer(); // int port= CatalinaUtil.getPort(host); // Disallow any direct access to resources under WEB-INF or META-INF MessageBytes requestPathMB = request.getRequestPathMB(); if ((requestPathMB.startsWithIgnoreCase("/META-INF/", 0)) || (requestPathMB.equalsIgnoreCase("/META-INF")) || (requestPathMB.startsWithIgnoreCase("/WEB-INF/", 0)) || (requestPathMB.equalsIgnoreCase("/WEB-INF"))) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // Select the Wrapper to be used for this Request Wrapper wrapper = request.getWrapper(); if (wrapper == null || wrapper.isUnavailable()) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // Acknowledge the request try { response.sendAcknowledgement(); } catch (IOException ioe) { container.getLogger().error(sm.getString("standardContextValve.acknowledgeException"), ioe); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, ioe); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } if (request.isAsyncSupported()) { request.setAsyncSupported(wrapper.getPipeline().isAsyncSupported()); } wrapper.getPipeline().getFirst().invoke(request, response); }
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 ava2s . c o 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;/* w w w.java 2 s . c om*/ 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(); }