【发布时间】:2019-06-11 08:36:47
【问题描述】:
@ControllerAdvice 中 MaxUploadSizeExceededException 的 @ExceptionHandler 返回的 Response 无法在 swagger-ui.html 中显示。
我正在为我的 RESTful 应用程序使用 Spring Boot。并使用 swagger-ui 来使用 RESTful API。我的 RESTful API 之一是使用 Spring 的 MultipartFile 上传文件。
文件大小有限制,当上传的文件大小超过限制时,会抛出如下异常。 [请求处理失败;嵌套异常是 org.springframework.web.multipart.MaxUploadSizeExceededException: 超出最大上传大小...
为了处理此异常以向客户端返回自定义的错误消息,我使用了@ControllerAdvice 中的@ExceptionHandler 来返回响应。下面是我的代码。
@ControllerAdvice
public class GlobalControllerExceptionHandler{
@ExceptionHandler(MaxUploadSizeExceededException.class)
@ResponseBody
public ResponseEntity<?> maxUploadSizeExceededException(MaxUploadSizeExceededException e) {
String bodyJson = "{\"ErrorMessage\":\"Maximum upload size exceeded.\"}";
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).contentType(MediaType.TEXT_PLAIN).body(bodyJson);
}
}
我想在swagger-ui.html中看到的是这样的:
Response Body:
{"ErrorMessage":"Maximum upload size exceeded."}
Response Code:
500
但是现在,我没有看到任何内容:
Response Body:
no content
Response Code:
0
我在浏览器控制台上看到的一个异常症状是,请求头
临时标题显示“显示临时标题”:
!Provisional headers are shown
Accept: */*
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryf7WjEeoDHtIm3ly1
Origin: http://localhost:8080
Referer: http://localhost:8080/SpringApp/swagger-ui.html
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36
X-Requested-With: XMLHttpRequest
我搜索了“显示临时标头”,有人解释说,如果显示此类消息,则表示该请求实际上未发送。但就我而言,我实际上在 Spring Application 服务器端收到了请求,我什至可以点击 @ErrorHandler 方法“maxUploadSizeExceededException”。
【问题讨论】:
标签: java spring-boot curl error-handling swagger-ui