【问题标题】:@ExceptionHandler annotation in controller does not catching MaxUploadSizeExceededException控制器中的 @ExceptionHandler 注释没有捕获 MaxUploadSizeExceededException
【发布时间】:2017-03-09 01:01:47
【问题描述】:

我正在尝试一件非常简单的事情 - 捕获与文件上传相关的 MaxUploadSizeExceededException 错误。

这是我的 spring-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 的方法。

非常感谢您提供有关其他内容的帮助或指示。

【问题讨论】:

    标签: spring spring-mvc


    【解决方案1】:

    您能否尝试更改 ExceptionHandler 以查找 LimitExceededException 和 MultiPartException 而不是子异常?

    【讨论】:

    • 我都试过了,但是都不管用,在我看来,控制器中的 ExceptionHandler 只捕获了在这个控制器中触发的异常。
    【解决方案2】:

    尝试使用@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/> 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-07
      • 2018-03-31
      • 2013-01-03
      • 1970-01-01
      • 1970-01-01
      • 2016-12-16
      • 2020-06-05
      • 1970-01-01
      相关资源
      最近更新 更多