Jersey を使用して構築された 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 です。