[英]JAXB writing to OutputStream inside writeTo method
我一直试图在MessageBodyWriter接口的writeTo实现方法内直接将String写入OutputStream。 我想在try catch块中执行此操作,以在捕获异常时发送消息。 但是,当我通过程序调试时,我意识到String永远不会写入OutputStream(大小= -1)。
代码看起来像这样:
public void writeTo(final Object entityObject, final Class<?> aClass, final Type type,
final Annotation[] annotations, final MediaType mediaType,
final MultivaluedMap<String, Object> stringObjectMultivaluedMap,
final OutputStream outputStream) throws IOException, WebApplicationException {
try{
throw new JAXBException("error");
}catch(JAXBException j){
outputStream.write("HI".getBytes());
outputStream.flush();
}
新答案
您可以利用可以从MessageBodyWriter中的writeTo方法引发的WebApplicationException。
public void writeTo(DataObject dataObject, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> multivaluedMap, OutputStream outputStream) throws IOException, WebApplicationException {
try {
throw new JAXBException("error");
} catch(JAXBException e) {
Response response = Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity("HI")
.type("text/plain")
.build();
throw new WebApplicationException(response);
}
}
原始答案
在我看来,最好从MessageBodyWriter抛出JAXBException,然后创建一个ExceptionMapper来记录问题:
@Provider
public class JAXBExceptionMapper implements ExceptionMapper<JAXBException> {
public Response toResponse(JAXBException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity(e.getMessage());
.type("text/plain").build();
}
}
这将允许您返回指示发生问题的响应代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.