是否可以在JAX-RS / JAXB Web服务中捕获SAXParseException?

时间:2010-08-03 20:27:19

标签: java jaxb jax-rs saxparseexception

我想在JAX-RS Web服务请求中检查正文中是否包含有效的XML。但是,这段代码:

@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
}

返回500内部服务器错误,而不是预期的400错误。有没有办法捕捉异常?

异常堆栈跟踪的开始是:

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)

1 个答案:

答案 0 :(得分:2)

您可以使用例外映射器。抛出异常时会将其转换为响应代码:

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();
    }

}

参考: