请原谅任何可怕的错误,由于项目要求,我在大约一周前完全掌握了 Kotlin 和一些 Spring。我正在尝试创建一个简单的 RESTful API,其端点可以通过 Multipart 接受文件。稍后,API 之外会有一些页面显示 HTML,我为此使用Koreander。据我所见,基于 Java 教程,异常处理应该像这样工作。
但是,对于 API,我为 MaxUploadSizeExceededException 定义的异常处理程序根本不会触发。我的应用程序.kt:
@SpringBootApplication
@EnableConfigurationProperties(StorageProperties::class)
class JaApplication {
@Bean fun koreanderViewResolver(): ViewResolver = KoreanderViewResolver()
}
fun main(args: Array<String>) {
runApplication<JaApplication>(*args)
}
我的控制器:
@RestController
@RequestMapping("/api")
@EnableAutoConfiguration
class APIController {
@PostMapping(
value = "/convert",
produces = arrayOf(MediaType.APPLICATION_JSON_VALUE)
)
fun convert(@RequestParam("file") multipartFile: MultipartFile): Result {
return Result(status = 0, message = "You have uploaded: ${multipartFile.getOriginalFilename()}.")
}
}
@ControllerAdvice
class ExceptionHandlers {
@ExceptionHandler(MultipartException::class)
fun handleException(e: MultipartException): String = Result(status = 1, message = "File is too large.")
}
}
当我试图通过 curl 发布一个大文件时,我收到一个 JSON 回复:
curl -F 'file=@path-to-large-file' http://localhost:8080/api/convert
{"timestamp":"2018-11-27T15:47:31.907+0000","status":500,"error":"Internal Serve
r Error","message":"Maximum upload size exceeded; nested exception is java.lang.
IllegalStateException: org.apache.tomcat.util.http.fileupload.FileUploadBase$Siz
eLimitExceededException: the request was rejected because its size (4294967496)
exceeds the configured maximum (529530880)","path":"/api/convert"}
Tomcat是否有可能不将此异常传递给Spring?如果是的话,我怎么能抓住这个?如果我可以将大小设置为无限制并在上传时检查文件大小,它也可以工作,尽管我需要在服务器开始接收文件之前这样做,并且我假设在我到达/api/convert端点时,为时已晚。
谢谢你的帮助。