我有一个使用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。