У меня есть служба REST, построенная с использованием Джерси.
Я хочу иметь возможность установить MIME моих собственных создателей исключений в зависимости от MIME, который был отправлен на сервер. application/json
возвращается при получении json и application/xml
при получении 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