Example usage for javax.servlet RequestDispatcher ERROR_MESSAGE

List of usage examples for javax.servlet RequestDispatcher ERROR_MESSAGE

Introduction

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

Prototype

String ERROR_MESSAGE

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

Click Source Link

Document

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

Usage

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:myfeed.user.ApiDocumentation.java

@Test
public void errorExample() throws Exception {
    this.mockMvc//from  w  w w  .jav  a  2  s  .  c o  m
            .perform(get("/error").requestAttr(RequestDispatcher.ERROR_STATUS_CODE, 400)
                    .requestAttr(RequestDispatcher.ERROR_REQUEST_URI, "/notes")
                    .requestAttr(RequestDispatcher.ERROR_MESSAGE,
                            "The tag 'http://localhost:8080/tags/123' does not exist"))
            .andDo(print()).andExpect(status().isBadRequest()).andExpect(jsonPath("error", is("Bad Request")))
            .andExpect(jsonPath("timestamp", is(notNullValue()))).andExpect(jsonPath("status", is(400)))
            .andExpect(jsonPath("path", is(notNullValue()))).andDo(document("error-example"));
}

From source file:io.spring.initializr.web.test.MockMvcClientHttpRequestFactory.java

@Override
public ClientHttpRequest createRequest(final URI uri, final HttpMethod httpMethod) throws IOException {
    return new MockClientHttpRequest(httpMethod, uri) {
        @Override//from  w w w . j a  v  a2 s  . c  om
        public ClientHttpResponse executeInternal() throws IOException {
            try {
                MockHttpServletRequestBuilder requestBuilder = request(httpMethod, uri.toString());
                requestBuilder.content(getBodyAsBytes());
                requestBuilder.headers(getHeaders());
                MockHttpServletResponse servletResponse = actions(requestBuilder).andReturn().getResponse();
                HttpStatus status = HttpStatus.valueOf(servletResponse.getStatus());
                if (status.value() >= 400) {
                    requestBuilder = request(HttpMethod.GET, "/error")
                            .requestAttr(RequestDispatcher.ERROR_STATUS_CODE, status.value())
                            .requestAttr(RequestDispatcher.ERROR_REQUEST_URI, uri.toString());
                    if (servletResponse.getErrorMessage() != null) {
                        requestBuilder.requestAttr(RequestDispatcher.ERROR_MESSAGE,
                                servletResponse.getErrorMessage());
                    }
                    // Overwrites the snippets from the first request
                    servletResponse = actions(requestBuilder).andReturn().getResponse();
                }
                byte[] body = servletResponse.getContentAsByteArray();
                HttpHeaders headers = getResponseHeaders(servletResponse);
                MockClientHttpResponse clientResponse = new MockClientHttpResponse(body, status);
                clientResponse.getHeaders().putAll(headers);
                return clientResponse;
            } catch (Exception ex) {
                throw new IllegalStateException(ex);
            }
        }

    };
}

From source file:com.example.ApiDocumentation.java

@Test
public void error() throws Exception {
    this.mockMvc/*from w w w . j  ava2s .  com*/
            .perform(get("/error").requestAttr(RequestDispatcher.ERROR_STATUS_CODE, 400)
                    .requestAttr(RequestDispatcher.ERROR_REQUEST_URI, "/orders")
                    .requestAttr(RequestDispatcher.ERROR_MESSAGE, "The order cannot be created."))
            .andExpect(status().isBadRequest()).andExpect(jsonPath("error", is("Bad Request")))
            .andExpect(jsonPath("timestamp", is(notNullValue()))).andExpect(jsonPath("status", is(400)))
            .andExpect(jsonPath("path", is(notNullValue())))
            .andDo(this.documentationHandler.document(responseFields(
                    fieldWithPath("error").description("The HTTP error that occurred, e.g. `Bad Request`"),
                    fieldWithPath("message").description("A description of the cause of the error"),
                    fieldWithPath("path").description("The path to which the request was made"),
                    fieldWithPath("status").description("The HTTP status code, e.g. `400`"),
                    fieldWithPath("timestamp")
                            .description("The time, in milliseconds, at which the error occurred"))));
}

From source file:edu.pitt.dbmi.ccd.anno.CCDAnnotationsTest.java

@Test
public void errorExample() throws Exception {
    this.mockMvc/* ww  w. j a  v  a2 s  .  co  m*/
            .perform(get("/error").requestAttr(RequestDispatcher.ERROR_STATUS_CODE, 404)
                    .requestAttr(RequestDispatcher.ERROR_REQUEST_URI, "/test")
                    .requestAttr(RequestDispatcher.ERROR_MESSAGE, "Not found"))
            .andExpect(status().isNotFound()).andExpect(jsonPath("timestamp", is(notNullValue())))
            .andExpect(jsonPath("status", is(404))).andExpect(jsonPath("error", is("Not Found")))
            .andExpect(jsonPath("message", is("Not found"))).andExpect(jsonPath("path", is(notNullValue())))
            .andDo(this.documentationResultHandler.document(
                    responseHeaders(headerWithName("Content-Type")
                            .description("The Content-Type of the payload, e.g. `application/hal+json`")),
                    responseFields(
                            fieldWithPath("timestamp").description("The time at which the error occurred"),
                            fieldWithPath("status").description("The HTTP status code"),
                            fieldWithPath("error").description("The HTTP error"),
                            fieldWithPath("message").description("A description of what caused the error"),
                            fieldWithPath("path").description("The path to which the request was made"))));
}

From source file:com.example.notes.ApiDocumentation.java

@Test
public void errorExample() throws Exception {
    this.mockMvc/*ww  w .j a v  a2 s. co  m*/
            .perform(get("/error").requestAttr(RequestDispatcher.ERROR_STATUS_CODE, 400)
                    .requestAttr(RequestDispatcher.ERROR_REQUEST_URI, "/notes")
                    .requestAttr(RequestDispatcher.ERROR_MESSAGE,
                            "The tag 'http://localhost:8080/tags/123' does not exist"))
            .andExpect(status().isBadRequest()).andExpect(jsonPath("error", is("Bad Request")))
            .andExpect(jsonPath("timestamp", is(notNullValue()))).andExpect(jsonPath("status", is(400)))
            .andExpect(jsonPath("path", is(notNullValue())))
            .andDo(this.documentationHandler.document(responseFields(
                    fieldWithPath("error").description("The HTTP error that occurred, e.g. `Bad Request`"),
                    fieldWithPath("message").description("A description of the cause of the error"),
                    fieldWithPath("path").description("The path to which the request was made"),
                    fieldWithPath("status").description("The HTTP status code, e.g. `400`"),
                    fieldWithPath("timestamp")
                            .description("The time, in milliseconds, at which the error occurred"))));
}

From source file:de.metas.ui.web.config.WebuiExceptionHandler.java

private void addErrorDetails(final Map<String, Object> errorAttributes,
        final RequestAttributes requestAttributes, final boolean includeStackTrace) {
    Throwable error = getError(requestAttributes);
    if (error != null) {
        while (error instanceof ServletException && error.getCause() != null) {
            error = ((ServletException) error).getCause();
        }/*  w  w w .  j a va2s.  com*/
        errorAttributes.put(ATTR_Exception, error.getClass().getName());
        addErrorMessage(errorAttributes, error);
        if (includeStackTrace && !isExcludeFromLogging(error)) {
            addStackTrace(errorAttributes, error);
        }
    }

    final Object message = getAttribute(requestAttributes, RequestDispatcher.ERROR_MESSAGE);
    if ((!StringUtils.isEmpty(message) || errorAttributes.get(ATTR_Message) == null)
            && !(error instanceof BindingResult)) {
        errorAttributes.put(ATTR_Message, StringUtils.isEmpty(message) ? "No message available" : message);
    }
}

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  ww w .  j a  v  a2 s .c  o 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();
}

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

/**
 * Handles an error status code.//  w w w. ja  v  a  2 s  . c o m
 * 
 * @return true if we've forwarded to an error page.
 */
private boolean handleErrorStatus(CauchoRequest request, CauchoResponse response, int code, String message)
        throws ServletException, IOException {
    if (code == HttpServletResponse.SC_OK || code == HttpServletResponse.SC_MOVED_TEMPORARILY
            || code == HttpServletResponse.SC_NOT_MODIFIED)
        return false;

    if (request.getRequestDepth(0) > 16)
        return false;

    else if (request.getAttribute(RequestDispatcher.ERROR_REQUEST_URI) != null) {
        return false;
    }

    response.killCache();

    String location = getErrorPage(code);

    if (location == null)
        location = _defaultLocation;

    WebApp webApp = getWebApp();

    if (webApp == null && _host == null)
        return false;

    if (location != null && !location.equals(request.getRequestURI())) {
        request.setAttribute(RequestDispatcher.ERROR_STATUS_CODE, new Integer(code));
        request.setAttribute(RequestDispatcher.ERROR_MESSAGE, message);
        request.setAttribute(RequestDispatcher.ERROR_REQUEST_URI, request.getRequestURI());

        String servletName = getServletName(request);

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

        try {
            RequestDispatcher disp = null;
            // can't use filters because of error pages due to filters
            // or security.
            if (webApp != null)
                disp = webApp.getRequestDispatcher(location);
            else if (_host != null)
                disp = _host.getWebAppContainer().getRequestDispatcher(location);

            // disp.forward(request, this, "GET", false);

            if (disp != null) {
                ((RequestDispatcherImpl) disp).error(request, response);
            } else
                return false;
        } catch (Throwable e) {
            sendServletError(e, request, response);
        }

        return true;
    }

    return false;
}