'Using zipOutPutStream, cannot change mediatype in exceptionhandler, when exception happens in Spring

In my post request endpoint, I want to generate ZIP File.

Here is endpoint:

public void downloadZipFile(@RequestBody final Parameters parameter, final HttpServletResponse response) throws FileReadingException, IOException {
    response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
    response.setHeader(CONTENT_DISPOSITION, HEADER_VALUE_STR);
    response.setStatus(HttpServletResponse.SC_OK);
    this.generateZipServiceImpl.generateZipFile(parameter, response);
}

I throw exception when something wrong happens in

this.generateZipServiceImpl.generateZipFile(parameter, response) P.S I write files in response.getOutPutStream();

I also have global exception handler:

@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(value = {FileReadingException.class, ResourceNotFoundException.class,
        UncheckedIOException.class, TimebaseConnectionException.class, SecuritiesStreamCannotCopyException.class })
public ResponseEntity<String> handleInternalServerErrors() {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.TEXT_PLAIN);
    return new ResponseEntity<>(INTERNAL_SERVER_ERROR_MESSAGE, headers, HttpStatus.INTERNAL_SERVER_ERROR);
}

But the result is that, if exception happens, user gets 200OK request with half-full ZIP file. I want to just return 500 SERVER_INTERNAL_ERROR. Can someone suggest me how can I do this?

In console log there is written:

WARN 40048 --- [nio-8080-exec-7] .m.m.a.ExceptionHandlerExceptionResolver : Resolved [com.deltix.timebaseinitializr.exceptions.SecuritiesStreamCannotCopyException: Can't Copy securities stream files]

but ExceptionHandler's method handleInternalServeErrors() don't change MediaType to TEXT_PLAIN and don't change STATUS CODE to INTERNAL_SERVER_ERROR too, so response is MediaType.OCTET-STREAM and 200OK.

Also ExceptionHandler's other methods work correctly(for example, returns BAD_REQUEST and changes MimeType from OCTET-STREAM to TEXT_PLANI), but there I don't write anything in response.getOutPutStream() thats the difference.

So I think I want something that forces spring to clear this outputstream and change mediatype



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source