Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

As I have set maximum file upload limit,I am getting

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

error while uploading file.It is giving 500 error to my api,I should I handle this error and return response in JSON format not an errorpage as provided in ErrorController

I want to catch that exception and give 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 that accepts document as follows

public class FileUploadSingleDTO {
@NotNull
    private Integer documentName;

    private Integer documentVersion;

    @NotNull
    private MultipartFile file;
}
like image 401
MasterCode Avatar asked Dec 09 '15 06:12

MasterCode


People also ask

What is default multipart file upload size in spring boot?

The default is 10MB.

How do you handle MaxUploadSizeExceededException?

Handling MaxUploadSizeExceededException In order to handle this exception, we can have our controller implement the interface HandlerExceptionResolver, or we can create a @ControllerAdvice annotated class.


2 Answers

As par I know you can handle the multipart file exception by 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";
  }
}
like image 61
Srinivas Rampelli Avatar answered Sep 19 '22 09:09

Srinivas Rampelli


Add a special exception handler into your Controller:

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

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

like image 30
theHacker Avatar answered Sep 21 '22 09:09

theHacker