JAXB 在 writeTo 方法中写入 OutputStream
我一直在尝试在 MessageBodyWriter 接口的 writeTo 实现方法内直接将 String 写入 OutputStream 。我想在 try catch 块内执行此操作,以便在捕获异常时发送消息。然而,当我调试程序时,我意识到字符串永远不会被写入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();
}
I have been trying to write a String directly to OutputStream inside the writeTo implementation method of MessageBodyWriter interface. I want to do this inside a try catch block to send a message when an exception gets caught. However, when I debug through the program, I realize that the String never gets written to the OutputStream (size = -1).
The code looks something like this:
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();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
新答案
您可以利用从 MessageBodyWriter 中的 writeTo 方法抛出的 WebApplicationException。
原始答案
在我看来,您最好从 MessageBodyWriter 中抛出 JAXBException,然后创建一个 ExceptionMapper 来记录问题:
这将允许您返回一个指示发生问题的响应代码。
NEW ANSWER
You could leverage the WebApplicationException that can be thrown from the writeTo method in MessageBodyWriter.
ORIGINAL ANSWER
In my opinion you are better of throwing the JAXBException from the MessageBodyWriter, and then creating an ExceptionMapper to log the problem:
This will allow you to return a response code that indicates that a problem occurred.