多部分文件 Upload:Size 在 spring 引导 return JSON 错误消息中超出异常

Multipart File Upload:Size exceed exception in spring boot return JSON error message

因为我设置了最大文件上传限制,所以我得到

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

上传 file.It 时出错,我的 api 收到 500 错误,我应该处理这个错误并且 return 响应 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;
}

在您的控制器中添加一个特殊的异常处理程序:

@ExceptionHandler(FileSizeLimitExceededException.class)
public YourReturnType uploadedAFileTooLarge(FileSizeLimitExceededException e) {
    /*...*/
}

(如果这不起作用,您必须在配置中启用异常处理。通常 Spring 默认情况下会这样做。)

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

@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";
  }
}