Example usage for javax.servlet RequestDispatcher ERROR_STATUS_CODE

List of usage examples for javax.servlet RequestDispatcher ERROR_STATUS_CODE

Introduction

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

Prototype

String ERROR_STATUS_CODE

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

Click Source Link

Document

The name of the request attribute under which the response status 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:org.tec.webapp.web.ErrorServlet.java

/**
 * process the error//from  w  w  w  .  j  a  v  a  2 s. c om
 * @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:myfeed.user.ApiDocumentation.java

@Test
public void errorExample() throws Exception {
    this.mockMvc//from  ww  w.j a  v 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   www.  j  av  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:de.whs.poodle.PoodleErrorAttributes.java

@Override
public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace) {
    Map<String, Object> errorAttributes = new HashMap<>();

    Throwable error = getError(requestAttributes);

    String message = null;/*  w  ww  . j  a v a 2s  .c  o m*/

    if (error != null) {
        /* RepositoryExceptions contain messageCodes for localization.
         * If the error was a RepositoryException, create the corresponding
         * text with the messageSource. We use this a lot with
         * BadRequestException to localize responses to the client. */
        if (error instanceof RepositoryException) {
            RepositoryException daoExc = (RepositoryException) error;
            if (daoExc.getMessageCode() != null) {
                Locale locale = LocaleContextHolder.getLocale();
                message = messageSource.getMessage(daoExc.getMessageCode(), daoExc.getMessageCodeArgs(),
                        locale);
            }
        }

        // show a more specific error on database connection failures
        if (error instanceof CannotGetJdbcConnectionException)
            message = "error connecting to database (" + error.getMessage() + ")";

        log.error("Error", error);
    }

    int status = (int) requestAttributes.getAttribute(RequestDispatcher.ERROR_STATUS_CODE,
            RequestAttributes.SCOPE_REQUEST);

    if (message == null)
        message = HttpStatus.valueOf(status).getReasonPhrase();

    errorAttributes.put("status", status);
    errorAttributes.put("message", message);

    return errorAttributes;
}

From source file:com.example.ApiDocumentation.java

@Test
public void error() throws Exception {
    this.mockMvc//from  www.  j a  v a2 s .  c  om
            .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//  www  .  j  a v a  2s.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/*from  w ww .j  a v a  2  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 addStatus(final Map<String, Object> errorAttributes, final RequestAttributes requestAttributes) {
    Integer status = null;//  w  ww . ja  v  a 2s .  c  o  m

    //
    // Extract HTTP status from EXCEPTION_HTTPSTATUS map
    final Throwable error = getError(requestAttributes);
    if (error != null) {
        final Class<? extends Throwable> errorClass = error.getClass();
        status = EXCEPTION_HTTPSTATUS.entrySet().stream().filter(e -> isErrorMatching(e.getKey(), errorClass))
                .map(e -> e.getValue().value()).findFirst().orElse(null);
    }

    //
    // Extract HTTP status from attributes
    if (status == null) {
        status = getAttribute(requestAttributes, RequestDispatcher.ERROR_STATUS_CODE);
    }

    if (status == null) {
        errorAttributes.put(ATTR_Status, 999);
        errorAttributes.put(ATTR_Error, "None");
        return;
    }
    errorAttributes.put(ATTR_Status, status);
    try {
        errorAttributes.put(ATTR_Error, HttpStatus.valueOf(status).getReasonPhrase());
    } catch (final Exception ex) {
        // Unable to obtain a reason
        errorAttributes.put(ATTR_Error, "Http Status " + status);
    }
}