gpt4 book ai didi

java - JAXB 在 writeTo 方法中写入 OutputStream

转载 作者:太空宇宙 更新时间:2023-11-04 08:43:13 26 4
gpt4 key购买 nike

我一直在尝试在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/

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