开发者

Is it possible to catch SAXParseException in JAX-RS/JAXB webservice?

I would like to check in a JAX-RS webservice request that valid XML was included in the body. However, this code:

@PUT
@Produces(MediaType.TEXT_XML)
@Consumes(MediaType.TEXT_XML)
@Path("/{objectID}")
public MyObject updateMyObject(@PathParam("objectID") String existingObjectID, JAXBElement<MyObject> object)
{
    MyObject udpatedObject = null;

    try
    {
        udpatedObject = object.getValue();
    }
    catch (Throwable ex)
    {
        throw new WebApplicationException(Response.Status.BAD_REQUEST);            
    }

    // carry one with processing
}

returns a 500 internal server error instead of the expected 400 error. Is there a way to catch the exception?

The start of the exception stack trace is:

Local Exception Stack: 
Exception [EclipseLink-25004] (Eclipse Persistence Services - 2.0.1开发者_运维技巧.v20100213-r6600): org.eclipse.persistence.exceptions.XMLMarshalException
Exception Description: An error occurred unmarshalling the document
Internal Exception: org.xml.sax.SAXParseException: Premature end of file.
at org.eclipse.persistence.exceptions.XMLMarshalException.unmarshalException(XMLMarshalException.java:92)


You can use an exception mapper. When the exception is throw will be translated into a response code:

import javax.persistence.NoResultException;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

@Provider
public class XMLMarshalExceptionMapper implements ExceptionMapper<XMLMarshalException> {

    public Response toResponse(XMLMarshalException exception) {
        return Response.status(Response.Status.BAD_REQUEST).build();
    }

}

Refer to:

  • https://jsr311.dev.java.net/nonav/javadoc/javax/ws/rs/ext/ExceptionMapper.html
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜