我使用Jersey构建了REST服务。
我希望能够根据发送到服务器的MIME设置自定义异常编写器的MIME。收到json时返回application/json
,收到xml时返回application/xml
。
现在我硬编码application/json
,但这使得XML客户端处于黑暗中。
public class MyCustomException extends WebApplicationException {
public MyCustomException(Status status, String message, String reason, int errorCode) {
super(Response.status(status).
entity(new ErrorResponseConverter(message, reason, errorCode)).
type("application/json").build());
}
}
我可以使用哪种上下文来获取当前请求Content-Type
?
谢谢!
对于对完整解决方案感兴趣的任何人:
public class MyCustomException extends RuntimeException {
private String reason;
private Status status;
private int errorCode;
public MyCustomException(String message, String reason, Status status, int errorCode) {
super(message);
this.reason = reason;
this.status = status;
this.errorCode = errorCode;
}
//Getters and setters
}
与ExceptionMapper
@Provider
public class MyCustomExceptionMapper implements ExceptionMapper<MyCustomException> {
@Context
private HttpHeaders headers;
public Response toResponse(MyCustomException e) {
return Response.status(e.getStatus()).
entity(new ErrorResponseConverter(e.getMessage(), e.getReason(), e.getErrorCode())).
type(headers.getMediaType()).
build();
}
}
其中ErrorResponseConverter是自定义JAXB POJO
答案 0 :(得分:25)
您可以尝试将@javax.ws.rs.core.Context javax.ws.rs.core.HttpHeaders字段/属性添加到根资源类,资源方法参数或自定义javax.ws.rs。 ext.ExceptionMapper并调用HttpHeaders.getMediaType()。
答案 1 :(得分:15)
headers.getMediaType()以实体的媒体类型响应,而不是Accept标头。转换异常的适当方法是使用Accept标头,以便客户端以他们请求的格式获取响应。鉴于上述解决方案,如果您的请求如下所示(注意JSON接受标头,但是XML实体),您将获得XML。
POST http://localhost:8080/service/giftcard/invoice?draft=true HTTP/1.1 Accept: application/json Authorization: Basic dXNlcjp1c2Vy Content-Type: application/xml User-Agent: Jakarta Commons-HttpClient/3.1 Host: localhost:8080 Proxy-Connection: Keep-Alive Content-Length: 502 <?xml version="1.0" encoding="UTF-8" standalone="yes"?><sample><node1></node1></sample>
使用Accept标头再次正确实现:
public Response toResponse(final CustomException e) {
LOGGER.debug("Mapping CustomException with status + \"" + e.getStatus() + "\" and message: \"" + e.getMessage()
+ "\"");
ResponseBuilder rb = Response.status(e.getStatus()).entity(
new ErrorResponseConverter(e.getMessage(), e.getReason(), e.getErrorCode()));
List<MediaType> accepts = headers.getAcceptableMediaTypes();
if (accepts!=null && accepts.size() > 0) {
//just pick the first one
MediaType m = accepts.get(0);
LOGGER.debug("Setting response type to " + m);
rb = rb.type(m);
}
else {
//if not specified, use the entity type
rb = rb.type(headers.getMediaType()); // set the response type to the entity type.
}
return rb.build();
}