Catch a SAXNotRecognizedException in Jersey during a POST operation

I play and convert a 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 the XML message. This way, I can detect when the user sends bad XML to the POST request and returns an XML Error response, unlike the standard HTML 400/500 error page.

Is there something similar in jersey? I tried to create an exception mapping class

 @Provider public class HttpMessageNotReadableException implements ExceptionMapper<org.xml.sax.SAXNotRecognizedException> { 

but this does not seem to catch any incoming errors, just when I exclude the exception from the resource class.

So, I thought that my method would get a string and do de-serialization and catch any errors:

 @POST @Path("/product") public Response createProduct(String createRequest) { try { // de-serialize // do work ... } catch ... 

instead

 @POST @Path("/product") public Response createProduct(CreateProduct createRequest) { // do work ... 

but this does not seem right, it will just pollute all my classes with the same error checking.

I also read about implementing my own reader using

 @Provider class MyXmlReader implements MessageBodyReader { 

but this is like re-creating the wheel, since JAXB is already de-serializing, I just want to catch the error.

Does anyone know if there is a better way to catch bad incoming XML?

+4
source share
1 answer

Jersey uses the same @Provider approach that 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 say so).

Have you tried to catch JAXB exceptions?

 import javax.ws.rs.core.Response; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider; import javax.xml.bind.JAXBException; @Provider public class JAXBExceptionMapper implements ExceptionMapper<JAXBException> { public Response toResponse(JAXBException exception) { return Response.status(Status.BAD_REQUEST).build(); } } 
+2
source

Source: https://habr.com/ru/post/1437910/


All Articles