【问题标题】:Spring MVC - handle exception with @ExceptionHandler doesn't render new viewSpring MVC - 使用@ExceptionHandler 处理异常不会呈现新视图
【发布时间】:2011-07-24 20:08:51
【问题描述】:

我似乎遇到了 Spring 的限制 - 我有一个简单的案例要处理 - 我正在模拟服务方法的异常:

@RequestMapping( method = RequestMethod.POST )
public String register( @RequestParam( "mail" ) String mail ){
    throw new IllegalStateException();
}

并尝试通过以下方式处理新请求:

@RequestMapping( value = "/exception_location" )
@ExceptionHandler( IllegalStateException.class )
public String handleException( IllegalStateException ex ){
    return "exception_view";
}

我的 web.xml:

<error-page>
    <exception-type>java.lang.IllegalStateException</exception-type>
    <location>/exception_location</location>
</error-page>

发生的情况是,handleException 确实被触发了,但异常视图没有在客户端上呈现。 Spring配置OK还是不需要web.xml中的条目?我是否遗漏了一些可能导致处理程序没有被调用的原因? 任何反馈表示赞赏。 谢谢。

【问题讨论】:

    标签: java model-view-controller spring exception view


    【解决方案1】:

    我发现了问题——抛出异常的方法需要与处理程序方法在同一个控制器中。我在同一个控制器中移动了这两种方法,一切正常。

    【讨论】:

      【解决方案2】:

      Ek,这对我来说似乎很奇怪。如果使用 Spring 的异常处理功能,则不需要 web.xml 中的条目。此外,通常您不会混合搭配@RequestMapping 和@ExceptionHandler。简而言之,您只需要...

      @ExceptionHandler( IllegalStateException.class )
      public String handleException( IllegalStateException ex ){
          return "exception_view";
      }
      

      【讨论】:

      • 感谢您的回复。不幸的是,这样做根本不会触发 handleException 方法。
      • 哇,你确定吗?您是否通过调试验证了这一点?我知道它可以工作,因为我一直在使用它(实际上就在昨天)。
      • 是的,我调试了它,它根本没有被调用。我会继续挖掘,也许有些东西我没有正确设置。谢谢。
      猜你喜欢
      • 2011-05-12
      • 2019-11-23
      • 2016-04-27
      • 2012-08-13
      • 2011-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多