2017-03-08 129 views
0

我正在尝试一个非常简单的事情 - 捕获与文件上载相关的错误MaxUploadSizeExceededException控制器中的@ExceptionHandler批注无法捕获MaxUploadSizeExceededException

下面是我的春天servlet.xml中的相关位:

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

而这里的控制器中的@ExceptionHandler方法,也负责处理文件上传的东西

@ExceptionHandler(MaxUploadSizeExceededException.class) 
public String handleException(MaxUploadSizeExceededException e, RedirectAttributes redirectAttributes) { 
    redirectAttributes.addFlashAttribute("uploadErrorMessage", e.getCause().getMessage()); 
    return "redirect:/page"; 
} 

文件上传工作正常。但是,当我使用超出大小限制的文件进行测试时,会抛出错误,并且从不调用ExceptionHanler的方法。

任何帮助或指示什么其他寻找/ at将不胜感激。

回答

0

您可以尝试更改ExceptionHandler以查找LimitExceededException和MultiPartException,而不是子例外?

+0

我试过了,但它不起作用,在我看来,控制器中的ExceptionHandler只捕获在此控制器中触发的异常。 – user2602584

0

尝试使用@ControllerAdvice创建一个单独的类,这将处理来自所有控制器的异常。

@ControllerAdvice 
public class ExceptionControllerAdvice { 

    @ExceptionHandler(MaxUploadSizeExceededException.class) 
public String handleException(MaxUploadSizeExceededException e, RedirectAttributes redirectAttributes) { 
    redirectAttributes.addFlashAttribute("uploadErrorMessage", e.getCause().getMessage()); 
    return "redirect:/page"; 
} 
} 

因此,如果我们在@ControllerAdvice类中定义的方法上我们@ExceptionHandler注解,它将被应用到所有控制器。

您必须在spring-servlet.xml文件中定义以下内容。

<mvc:annotation-driven/>