SpringBoot / Kotlin:Multipart MaxUploadSizeExceededException处理程序不会触发

时间:2018-11-27 15:55:58

标签: spring kotlin multipart exceptionhandler

请原谅任何可怕的错误,由于项目要求,我从字面上完全了解了Kotlin,大约一周前的某个春天。我正在尝试创建一个简单的RESTful API,其端点可以通过Multipart接受文件。稍后,API外面将有几页显示HTML,为此我正在使用Koreander。据我所知,并且基于Java教程,异常处理应该像这样工作。

对于API,我为MaxUploadSizeExceededException定义的异常处理程序根本不会触发。我的application.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 端点,为时已晚。

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

发现了问题。我会将其发布给将来可能会遇到相同问题的其他人。

@ControllerAdvice
class ExceptionHandlers():ResponseEntityExceptionHandler() {

    @ExceptionHandler(MaxUploadSizeExceededException::class)
    fun handleException(e: MultipartException, request:WebRequest): ResponseEntity<Any> {
        return handleExceptionInternal(e, Result(message = "File is too large."), HttpHeaders(), HttpStatus.PAYLOAD_TOO_LARGE, request)
    }
}