【发布时间】:2021-11-17 13:34:40
【问题描述】:
如何在springboot中返回错误并关闭Closeable类? 当我在 springboot 中遇到一些错误并关闭一个可关闭的类时返回 200 OK
我不需要关闭 Closeable 吗?有没有办法在springboot上处理这个?
CSVPrinter csvPrinter;
try{
csvPrinter = new CSVPrinter(httpServletResponse.getWriter() , CSVFormat.DEFAULT);
System.out.println(1/0); // force exception to jump into catch
}catch (Exception e) {
e.printStackTrace();
try { csvPrinter.close(true); } catch (IOException e1) { e1.printStackTrace(); } // has returned 200 OK when closing CSVPrinter
throw new RuntimeException("Error"); // this are been called but was already returned 200
}
我尝试过 try-with-resources 但也没有成功
try( final CSVPrinter csvPrinter = new CSVPrinter( httpServletResponse.getWriter() , CSVFormat.DEFAULT) ){
System.out.println(1/0); // // force exception to jump into catch
}catch (Exception e) { // has returned 200 OK
throw new RuntimeException("Error"); // this are been called but was already returned 200
}
我在控制器中注入 httpResponse
@GetMapping("/export")
public void exportInCsv(
ExportRequest exportRequest,
HttpServletResponse httpServletResponse // inject httpreponse
){
exportService.writeResponse(exportRequest,httpServletResponse);
}
我没有控制器异常处理程序
【问题讨论】:
-
我不完全理解你的问题。 “我已经尝试过尝试资源但没有成功”是什么意思
-
我用
try-with-resources刷新了添加示例的帖子,但我得到了 200 OK 甚至抛出任何异常 -
如果异常真的被抛出,这是不可能的。你能展示整个 RestController 吗?你定义了 ExceptionHandler 吗?
-
我不知道为什么会这样。我用控制器和处理程序异常信息刷新了帖子
-
为什么要直接写回复?
标签: spring-boot try-catch autocloseable