开发者

Spring MVC - handle exception with @ExceptionHandler doesn't render new view

开发者 https://www.devze.com 2023-02-20 14:50 出处:网络
I seem to be up against a limitation of Spring - I have a simple case to handle - I\'m simulating an exception from a service method:

I seem to be up against a limitation of Spring - I have a simple case to handle - I'm simulating an exception from a service method:

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

and trying to handle the new request via:

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

my web.xml:

<error-page>
    <exception-type>java.lang开发者_StackOverflow社区.IllegalStateException</exception-type>
    <location>/exception_location</location>
</error-page>

What happens is that handleException does get triggered, but the exception view doens't get rendered on the client. Is the Spring configuration OK or is the entry in web.xml not needed? Am I missing something that may be the reason of the handler not getting called? Any feedback is appreciated. Thanks.


I have found the problem - the method throwing the exception needs to be in the same controller with the handler method. I moved both methods in the same controller and everything works fine.


Ek, this seems very odd to me. If you use Spring's exception handling features you don't need the entry in web.xml. Also, typically you don't mix-and-match @RequestMapping and @ExceptionHandler. In short, all you should need is...

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号