Issue
I am trying to extract Word document from JDBC resultset using Spring Boot . Everything is working fine , just that when there is some error , I am getting 500 Error along with an empty file . How do I prevent empty file from being generated.
@GetMapping(produces = "application/vnd.openxmlformats-officedocument.wordprocessingml.document", value = "export/word")
@ApiOperation(value = "Export table as word")
public void generateword(HttpServletResponse response, @RequestParam(required = true) String tableName,
@RequestParam(required = false) String search, @RequestParam(required = false) String searchColumn,
@RequestHeader(required = false, value = "x-remote-user") String username)
throws DataAccessException, IOException {
DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
String currentDateTime = dateFormatter.format(new Date());
String headerKey = "Content-Disposition";
String headerValue = "attachment; filename=" + tableName + "_" + currentDateTime + ".docx";
response.setHeader(headerKey, headerValue);
response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
if (StringUtils.hasLength(search)) {
describeDatabaseRepository.generateWord(tableName, username, search, searchColumn, response);
} else {
describeDatabaseRepository.generateWord(tableName, username, response);
}
}
Solution
I fixed the issue by putting in try catch block.
try {
DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
String currentDateTime = dateFormatter.format(new Date());
String headerKey = "Content-Disposition";
String headerValue = "attachment; filename=" + tableName + "_" + currentDateTime + ".docx";
response.setHeader(headerKey, headerValue);
response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
if (StringUtils.hasLength(search)) {
describeDatabaseRepository.generateWord(tableName, username, search, searchColumn, response);
} else {
describeDatabaseRepository.generateWord(tableName, username, response);
}
} catch (Exception e) {
response.reset();
response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
ABCError err = new ABCError();
err.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
err.setDevMessage(e.getMessage());
err.setMessage("Something went wrong.Could not generate the file.");
response.getWriter().write(objectMapper.writeValueAsString(err));
}
Answered By - Ladu anand