我正在尝试为JAX-RS编写自定义ExceptionMapper
类。我想以某种方式从JAX-RS javax.ws.rs.core.Response
对象中读取原始请求的URI。
当我在调试模式下使用IntelliJ IDEA检查响应对象时,我可以在以下路径中看到此信息:响应>上下文> solveUri在哪里
context
的类型为org.glassfish.jersy.client.ClientResponse
。这个类有一个resolvedUri
变量,它保存了我需要的信息。
我能以某种方式获得此信息吗?我如何编写getRequestUri(response)
方法?
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();
}
}
答案 0 :(得分:1)
使用
@Context private HttpServletRequest servletRequest;
并使用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();
}
}