Search code examples
javajerseyjersey-2.0jersey-client

How to get the original requested URI from JAX-RS javax.ws.rs.core.Response


I am trying to write a custom ExceptionMapper class for JAX-RS. I would like to read somehow the original requested URI from the JAX-RS javax.ws.rs.core.Response object.

When I check the response object with IntelliJ IDEA in debug mode then I can see this info under the following path: response > context > resolvedUri where
type of the context is org.glassfish.jersy.client.ClientResponse. This class has a resolvedUri variable which holds the info I need.

Can I get this info somehow? How I can write my getRequestUri(response) method?

public class MyExceptionMapper implements ExceptionMapper<WebApplicationException> {

    @Override
    public Response toResponse(WebApplicationException error) {

        Response response = error.getResponse();
        ErrorResponse errorResponse = ErrorResponseBuilder
                .builder()
                .httpStatus(getDefaultStatusCodeIfNull(response))
                .errorMessage(getCustomErrorMessage(response))
                .requestedUri(getRequestedUri(response)) <--------- HOW TO READ IT?
                .build();

        return Response
                .status(errorResponse.getHttpStatus())
                .type(ExtendedMediaType.APPLICATION_JSON)
                .entity(errorResponse)
                .build();
    }
}

Solution

  • Use

    @Context private HttpServletRequest servletRequest;

    And use HttpServletRequest.getRequestURI()

    public class MyExceptionMapper implements 
         ExceptionMapper<WebApplicationException> {
    
        @Context
        private HttpServletRequest servletRequest;
    
        @Override
        public Response toResponse(WebApplicationException error) {
    
            Response response = error.getResponse();
            ErrorResponse errorResponse = ErrorResponseBuilder
                    .builder()
                    .httpStatus(getDefaultStatusCodeIfNull(response))
                    .errorMessage(getCustomErrorMessage(response))
                    .requestedUri(servletRequest.getRequestURI())
                    .build();
    
            return Response
                   .status(errorResponse.getHttpStatus())
                   .type(ExtendedMediaType.APPLICATION_JSON)
                   .entity(errorResponse)
                   .build();
        }
    }