swagger-ui.html中无法显示@ExceptionHandler为@ControllerAdvice中的MaxUploadSizeExceededException返回的响应。
我正在将Spring Boot用于RESTful应用程序。并使用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
我在浏览器控制台上看到的一种异常症状是,请求 header
临时 header 显示“显示临时 header ”:
!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
我搜索了“显示临时 header ”,有人解释说,如果显示此类消息,则意味着实际上未发送请求。但就我而言,我实际上是在Spring Application服务器端获得请求的,甚至可以使用@ErrorHandler方法“maxUploadSizeExceededException”。
最佳答案
Swagger不会解析您的Java实现。
如果要向文档中添加更多信息,则必须使用Swagger批注:
https://github.com/swagger-api/swagger-core/wiki/Annotations-1.5.X
在您的情况下,例如:
@ApiResponses(value = {
@ApiResponse(code = 500, message = "Maximum upload size exceeded.")
})
但是您必须将此注释添加到RestController中。昂首阔步不考虑ControllerAdvice。
关于java - 由@ControllerAdvice中的@ExceptionHandler返回的ResponseEntity不能在swagger-ui.html中显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54230941/