小编典典

分段文件上传:大小超出Spring Boot异常返回JSON错误消息

spring-boot

由于我设置了最大文件上传限制,

org.apache.tomcat.util.http.fileupload.FileUploadBase$FileSizeLimitExceededException: The field file exceeds its maximum permitted size of 2097152 bytes

上载文件时出错。它给我的api带来了500错误,我应该处理此错误并以JSON格式(不是提供的错误页)返回响应ErrorController

我想捕获该异常,但不给出JSON响应ErrorPage

@RequestMapping(value="/save",method=RequestMethod.POST)
    public ResponseDTO<String> save(@ModelAttribute @Valid FileUploadSingleDTO fileUploadSingleDTO,BindingResult bindingResult)throws MaxUploadSizeExceededException
    {
        ResponseDTO<String> result=documentDetailsService.saveDocumentSyn(fileUploadSingleDTO, bindingResult);

        return result;

    }

接受文件的DTO如下

public class FileUploadSingleDTO {
@NotNull
    private Integer documentName;

    private Integer documentVersion;

    @NotNull
    private MultipartFile file;
}

阅读 426

收藏
2020-05-30

共1个答案

小编典典

据我所知,您可以使用此文件处理多部分文件异常。

@ControllerAdvice
public class MyErrorController extends ResponseEntityExceptionHandler {

Logger logger = org.slf4j.LoggerFactory.getLogger(getClass());

@ExceptionHandler(MultipartException.class)
@ResponseBody
String handleFileException(HttpServletRequest request, Throwable ex) {
    //return your json insted this string.
    return "File upload error";
  }
}
2020-05-30