我一直在尝试在MessageBodyWriter接口(interface)的writeTo实现方法中直接将字符串写入OutputStream。我想在 try catch block 内执行此操作,以便在捕获异常时发送消息。然而,当我调试程序时,我意识到字符串永远不会被写入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();
}
}
这将允许您返回指示出现问题的响应代码。
关于java - JAXB 在 writeTo 方法中写入 OutputStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4855575/