【发布时间】:2011-03-14 17:32:24
【问题描述】:
我有一个使用 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
【问题讨论】:
-
ErrorResponseConverter 类会是什么样子?
-
@Oskar:请向我们展示您对 ErrorResponseConverter 的实现。谢谢!
-
@dreboy 这将只是一些 POJO 将返回给包含错误信息的用户。你会为 Jackson/JAXB/whatever 注释它以支持各种内容类型。
-
@ach 我想通了。不过感谢您的回复!