Multipage file upload: oversize in spring error returning to original JSON message

As I set the maximum file upload limit, I get

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

when downloading a file. This gives 500 errors for my api, I have to handle this error and return a response in JSON , and not an error, as indicated in ErrorController

I want to catch this exception and give a JSON response not 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, which accepts the document as follows

 public class FileUploadSingleDTO { @NotNull private Integer documentName; private Integer documentVersion; @NotNull private MultipartFile file; } 
+5
source share
2 answers

As you know, you can handle the exception of a multi-page file using this.

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

Add a special exception handler to the controller:

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

(If this does not work, you should enable exception handling in your configuration. Normally, Spring does this by default.)

+2
source

Source: https://habr.com/ru/post/1237724/


All Articles