I have a REST service built using Jersey.
I want to be able to set the MIME of my own exception creators based on the MIME that was sent to the server. application/json returned when receiving json and application/xml when receiving xml.
Now I have hardcoded application/json code, but this makes the XML clients left in the dark.
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()); } }
In what context can I access current Content-Type requests?
Thank!
Response Based Update
For anyone interested in a complete solution:
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; }
Together with 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(); } }
Where ErrorResponseConverter is a custom JAXB POJO
java jersey mime jax-rs
Oskar Jul 12 2018-10-12T00: 00Z
source share