How to handle maximum file size Exception in Sprin

2020-06-03 04:13发布

问题:

I am using Spring Boot v1.2.5 for creating a REST Application. While uploading images, I have a check for maximum file size , which is provided the property :

multipart.maxFileSize= 128KB

in application.properties. This facility is provided by Spring Boot itself. Now the check is working properly. The question is, how do I handle the exception and return a message to the user that he can understand ?

Update 1----------

I wrote a method within my Controller, where I intend to handle the MultipartException, using @ExceptionHandler. It does not seem to work.

This is my code :

@ExceptionHandler(MultipartException.class)
@ResponseStatus(value = HttpStatus.PAYLOAD_TOO_LARGE)
public ApplicationErrorDto handleMultipartException(MultipartException exception){
    ApplicationErrorDto applicationErrorDto =  new ApplicationErrorDto();
    applicationErrorDto.setMessage("File size exceeded");
    LOGGER.error("File size exceeded",exception);
    return applicationErrorDto;
}

Update 2----------

After @luboskrnac pointed it out, I have managed to come up with a solution. We can use ResponseEntityExceptionHandler here to handle this particular case. I believe, we could also have used DefaultHandlerExceptionResolver, but ResponseEntityExceptionHandler will allow us to return a ResponseEntity, as opposed to the former, the methods of which will return ModelAndView. I have not tried it though.

This is the final code that I'm using to handle the MultipartException :

@ControllerAdvice
public class CustomResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {

private static final Logger LOGGER = Logger.getLogger(CustomResponseEntityExceptionHandler.class);

@ExceptionHandler(MultipartException.class)
@ResponseStatus(value = HttpStatus.PAYLOAD_TOO_LARGE)
@ResponseBody
public ApplicationErrorDto handleMultipartException(MultipartException exception){
    ApplicationErrorDto applicationErrorDto =  new ApplicationErrorDto();
    applicationErrorDto.setMessage("File size exceeded");
    LOGGER.error("File size exceeded",exception);
    return applicationErrorDto;
}
}

I am using Swagger for developing/documenting REST Apis. This is the response upon uploading a file that exceeds the size. Thanks.

回答1:

Spring Boot docs says:

You can also use regular Spring MVC features like @ExceptionHandler methods and @ControllerAdvice. The ErrorController will then pick up any unhandled exceptions.

As MultipartException seem to hapen before @Controller/@ExceptionHandler/@ControllerAdvice features comes into play, you should use ErrorController to handle it.

BTW, I found this thread in the meantime. you may want to take a look.