有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java JAXB在writeTo方法中写入OutputStream

我一直在尝试在MessageBodyWriter接口的writeTo实现方法中直接将字符串写入OutputStream。我想在try-catch块中执行此操作,以便在捕获异常时发送消息。然而,当我调试程序时,我意识到字符串永远不会写入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) 个答案

  1. # 1 楼答案

    新答案

    您可以利用WebApplicationException,它可以从MessageBodyWriter中的writeTo方法抛出

    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抛出JAXBEException,然后创建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();
        }
    
    }
    

    这将允许您返回指示出现问题的响应代码