【发布时间】:2019-03-11 02:04:11
【问题描述】:
我在 Spring MVC 控制器中遇到了一个关于 StreamingReponseBody 的奇怪问题。简单的控制器代码:
@RestController
public class ServerController {
@GetMapping("test")
StreamingResponseBody test(HttpServletResponse response) {
response.setContentType("text/csv");
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"test.csv\"");
return outputStream -> {
for (int i = 0; i < 5000; i++) {
outputStream.write("Hello".getBytes());
outputStream.write("\n".getBytes());
}
try {
Thread.sleep(2000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (true) {
throw new RuntimeException("wrong");
}
for (int i = 0; i < 5000; i++) {
outputStream.write("Hello2".getBytes());
outputStream.write("\n".getBytes());
}
};
}
}
加上一个控制器建议:
@ControllerAdvice
public class CustomControllerAdvice {
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleInternalServerError(Exception exception) {
System.out.println("Unexpected error " + exception);
return new ResponseEntity<>(exception.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
当我删除 throw 子句时,它就像一个魅力。当我在浏览器中输入 URL */test 时,我可以看到我可以下载文件 test.csv。它被正确传输了一段时间,我得到一个 200 HTTP 代码,我可以查看该文件。
但是抛出异常会导致代码做一些奇怪的事情。我没有收到 500 HTTP 代码,而是 200 HTTP 代码。在流的末尾,我得到一个“错误”的文本(异常文本 o_O)......这里发生了什么?为什么我没有收到 500 HTTP 代码。端点发送的数据不是完整的,但它说尽管有例外情况都可以。或者我应该使用其他一些流媒体机制,因为这个机制有问题?
感谢您的帮助!
【问题讨论】:
标签: java spring-mvc spring-boot exception-handling streaming