简体   繁体   中英

Spring MVC @ExceptionHandler failing to catch an exception

I'm using Spring MVC to receive a file that is being uploaded with a form. This is my Controller that receives the request and handles possible exceptions:

@RequestMapping(method = RequestMethod.POST, 
                headers = {"content-type=multipart/form-data"}, 
                produces = "application/xml")
public @ResponseBody MyStuff processFormUpload( @RequestParam("file") CommonsMultipartFile file) throws 
    //return beautiful xml response generated from the input file;
}

@ExceptionHandler(Exception.class)
public ModelAndView exceptionHandler(Exception ex, HttpServletResponse response) {
    //return pretty exception page;
}

This is how I initialized the file resolver:

<bean id="multipartResolver"
      class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="maxUploadSize" value="100000"/>
</bean>

Everything works beautifully even when exceptions are raised while generating the response. The only problem is when someone tries to upload a file that is bigger than the maxUploadSize . In this case the exceptionHandler does not catch the exception and the service returns an ugly Internal Error 500 caused by MaxUploadSizeExceededException .

How can I configure my web app to catch that kind of exception as well? I'd like to use @ExceptionHandlers and not having to change the project structure too much.

As far as my understanding goes, these exceptions are thrown during data binding, before the controller is actually reached, therefore resulting in a 500 and no calling of the exception handler method.

So far the only way I have figured out to handle what you have mentioned is for the controller to implement 'HandlerExceptionResolver' and provide implementation for:

    public ModelAndView resolveException(HttpServletRequest request,
        HttpServletResponse response, Object handler, Exception exception)

I agree, it does not look at elegant or flexible as an @ExceptionHandler. Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM