My RSS servlet uses try-with-resource for the OutputStream out
of the HttpServletResponse
and the writer for it. In some cases SomeException
is thrown whilst generating the RSS document, in which case I need to return an HTTP status 500 to the client:
try (ServletOutputStream out = response.getOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(out, "utf-8")) {
response.setContentType("text/xml");
// Generate RSS here
} catch (SomeException e) {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
return;
}
However, by the time response.sendError()
is called, the $out$ has already been closed and I get said IllegalStateException
saying that the response has already been committed (closing the stream seems to commit the response automatically ).
If I move the initialization of out
and writer
outside of the try-block and close them in a finally-block (the pre-Java7 way), the error code gets sent correctly.
I was wondering whether there's a way to keep using try-with-resource and still be able to return error codes in case of an exception.
Thanks!