异常处理程序不会返回正确的响应

时间:2017-12-06 07:48:03

标签: java spring spring-mvc tomcat exception-handling

我有以下签名的控制器方法:

@PostMapping("/rest_upload")
public DeferredResult<ResponseEntity> upload(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest request) throws IOException {

我有以下异常处理程序:

@ExceptionHandler(MultipartException.class)
@ResponseStatus(HttpStatus.PAYLOAD_TOO_LARGE)
@ResponseBody
public String handleMaxUploadSizeExceededException(MultipartException e) {
    logger.warn("MultipartException occurred", e);
    String rootCauseMessage = ExceptionUtils.getRootCauseMessage(e);
    return rootCauseMessage.substring(rootCauseMessage.indexOf(":") + 1);
}

当我发送大小(120MB)超过可配置最大值(100MB)的文件时,此处理程序会调用但是在浏览器中我看到以下内容:

enter image description here

和细节:

enter image description here

如何解决此问题?

1 个答案:

答案 0 :(得分:0)

这个bean解决了我的问题:

@Bean
public TomcatEmbeddedServletContainerFactory tomcatEmbedded() {
    TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();
    tomcat.addConnectorCustomizers((TomcatConnectorCustomizer) connector -> {
        // configure maxSwallowSize
        if ((connector.getProtocolHandler() instanceof AbstractHttp11Protocol<?>)) {
            // -1 means unlimited, accept bytes
            ((AbstractHttp11Protocol<?>) connector.getProtocolHandler()).setMaxSwallowSize(-1);
        }
    });
    return tomcat;
}