JAXB在writeTo方法中写入OutputStream

时间:2011-01-31 20:12:25

标签: java jaxb jax-ws jax-rs

我一直在尝试将Message直接写入MessageBodyWriter接口的writeTo实现方法中的OutputStream。我想在try catch块中执行此操作,以便在捕获异常时发送消息。但是,当我通过程序调试时,我意识到String永远不会被写入OutputStream(size = -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();
   }

1 个答案:

答案 0 :(得分:1)

新答案

您可以利用可以从 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();
    }

}

这将允许您返回表示发生问题的响应代码。