开发者

@ExceptionHandler doesn't handle the thrown exceptions

开发者 https://www.devze.com 2022-12-31 04:24 出处:网络
I have a method in my controller which will handle the exceptions thrown by the application. So I have a method like this one.

I have a method in my controller which will handle the exceptions thrown by the application. So I have a method like this one.

@Controller
public class ExceptionCo开发者_运维问答ntroller {

    @RequestMapping(value="/error")
    @ExceptionHandler(value={Exception.class, NullPointerException.class})
    public String showError(Exception e, Model model){
        return "tiles:error";
    }
}

And to try I if it works I throw a NullPointerException in another method in other method controller:

boolean a = true;
if(a){ 
    throw new NullPointerException();
}

After the exception is thrown it is printed in the JSP, but it doesn't go throw my showError() method (I've set a breakpoint there and it never enters). showError() method will catch the exception and will show different error pages depending on the exception type (though now it always shows the same error page). If I go to the url /error it shows the error page so the showError() method is OK.

I'm using Spring 3.

What can be the problem?

Thanks.


If you look at your logs, you'll probably see this:

java.lang.IllegalStateException: Unsupported argument [org.springframework.ui.Model] for @ExceptionHandler method

In other words, @ExceptionHandler methods are not permitted to declare a Model parameter (see docs).

Remove that parameter (which you're not using anyway), and it should work as expected.


if you want to handle exceptions globally (outside your controller), then you can use a @ControllerAdvice annotated class in which you put your @ExceptionHandler annotated methods.

see http://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc for an example. And http://blog.codeleak.pl/2013/11/controlleradvice-improvements-in-spring.html for the improvements being made in spring 4.

0

精彩评论

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

关注公众号