I am playing around and converting an Spring MVC REST project to use Jersey, and have a method in one of my classes annotated with
@ExceptionHandler(HttpMessageNotReadableException.class)
which will catch any exceptions during de-serialization of an XML message. This way I can detect when a user sends bad XML in a POST request and return an XML Error response as opposed to a 400/500 standard HTML error page.
Is there something similar in Jersey? I tried creating an exception mapping class
@Provider
public class HttpMessageNotReadableException
implements ExceptionMapper<org.xml.sax.SAXNotRecognizedException> {
but that doesn’t seem to catch any in-coming errors, just when I throw the exception from inside the resource class.
So I thought of having my method get the string and do the de-serialization and catch any errors:
@POST
@Path("/product")
public Response createProduct(String createRequest) {
try {
// de-serialize
// do work ...
} catch ...
instead of
@POST
@Path("/product")
public Response createProduct(CreateProduct createRequest) {
// do work ...
but that doesn’t seem right, just going to pollute all my classes with the same error checking.
I also read about implementing my own reader using
@Provider
class MyXmlReader implements MessageBodyReader {
but that just seems like re-inventing the wheel since JAXB is already doing the de-serialization, I just want to catch the error.
Anyone know if a better way to catch bad incoming XML?
Jersey uses the exact same
@Providerapproach than Spring (which is defined in JAX-RS). I don’t know how Spring un/marshall objects, but Jersey uses JAXB for XML and JSON by default (it can use Jackson for JSON if you tell it to do so).Have you tried to catch JAXB exceptions?