I'd like to allow clients to select an error response format using HTTP content negotiation.
E.g. given an endpoint
@Produces("application/json")
class MyService {
@GET
public String getSomething() {
if (currentTimeMilis() % 2 == 0) throw new MyException();
return "{ hello:\"world\" }";
}
and exception mapper:
class MyExceptionMapper implements ExceptionMapper<MyException> {
@Override
public Response toResponse(MyException ex) {
return status(BAD_REQUEST)
.entity(new MyDto(randomUUID(), ex.getMessage()))
.build();
}
}
and having two body writers, MyBodyWriter
and standard JacksonJsonProvider
.
I'd like to invoke one of the writers depending on the contents of Accept header, e.g.
Accept: application/json
-> invokesJacksonJsonProvider
Accept: application/vnd-mycompany-error, application/json
-> invokesMyBodyWriter
I had tried different approaches but all of them fail because the matched HttpRule
implies an application/json
content type.
The only workaround I've found is to inject the request headers into ExceptionMapper
and set the content type explicitly there -- but I don't like it.