gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:40:43 26 4
gpt4 key购买 nike

我想在 JAX-RS 网络服务请求中检查正文中是否包含有效的 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)

最佳答案

您可以使用异常映射器。抛出异常时会翻译成响应码:

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

}

引用:

关于java - 是否可以在 JAX-RS/JAXB web 服务中捕获 SAXParseException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3400520/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com