0

I write file to OutputStream (got from response) in Spring controller. The file is large and I write in loops of 4 KB. When all finished, in finally block I flush and close output stream. If all goes fine it is good.

But in case there is error midway writing the file, how to show error to user?

In catch block I tried forwarding to error jsp, redirecting to error.jsp, to html page, or writing in the OutputStream again like

outputstream.write('<html>...error happened...</html>'.getBytes())

But it allways shows OutputStream already obtained, or prev page stays in client side, and no way to show error. How to handle error in this case?

Hash
  • 4,647
  • 5
  • 21
  • 39
Cod
  • 1
  • 1
  • Have you taken a look at `@ControllerAdvice`? Suppose that what you're doing is either within something annotated as `@Controller` or `@RestController`. In that case you can simply have a `@ControllerAdvice` (along with an appropriate `@ExceptionHandler`) that should be fitting for handling any errors. – akortex May 28 '18 at 18:33
  • Hi Mikhail, thanks for response quickly. I am trying it now. Obe thing wanted to ask is, if i use above way, even if rep is already written, it will still work? – Cod May 28 '18 at 18:50
  • Can you please clarify a bit or even post some sample code in order to help you a bit more? – akortex May 28 '18 at 19:33
  • I have to write a file to output stream, and also send a cookie, for different purpose. The browser expects this cookie for another action. I could not set cookie in same response i had used to write the file. So I wrapped the response in MutableResponse. Got outputstream (out1) from original response and kept it. In next method, from the mutableresponse, got outputstream again (out2), set contenttype to inline attachment, application/pdf, wrote file in loops of fixed buffer size, in finally block flushed and closed out2. – Cod May 29 '18 at 12:24
  • In original method, got content from the written mutableresponse, set it on out1, added cookie to out1, then close out1. Then return a null modelandview. So the file and cookie reach client. In case there is an unexpected error when adding cookie, it goes to catch block. Here, I return a modelandview to my error jsp. In this place, it says outputstream already obtained and jsp is not able to handle it, hence prints out the stack trace, which I do not want. I want to show a one line general error and in a jsp. Sorry not able to write code as it does not allow to format. – Cod May 29 '18 at 12:25
  • Don't use ` finally` to close the stream. [Use `try`-with-resources](https://stackoverflow.com/a/56112599/545127). – Raedwald May 13 '19 at 13:04

0 Answers0