Alex Rivera | Logout

Exception handler in Spring MVC

Asked 2011-07-19T04:32:29.847
21

I want to create an exception handler which will intercept all controllers in my project. Is that possible to do? Looks like I have to put a handler method in each controller. Thanks for your help. I have a spring controller that sends Json response. So if an exception happens I want to send an error response which can be controlled from one place.

Edit
Report

2 Answers

15

Since Spring 3.2 you can use @ControllerAdvice annotation. You can declare an @ExceptionHandler method within an @ControllerAdvice class in which case it handles exceptions from @RequestMapping methods from all controllers.

@ControllerAdvice
public class MyGlobalExceptionHandler {

    @ExceptionHandler(value=IOException.class)
    public @ResponseBody String iOExceptionHandler(Exception ex){
        //
        //
    }

    // other exception handler methods
    // ...

}
answered 2013-04-18T06:54:14.287
9

An abstract class where you define the exception handlers will do. And then make your controllers inherit it.

answered 2011-07-19T05:26:36.793

Your Answer