Exception Handling – part 2 – Globally

In our previous article we have seen how to handle exception that are thrown from our controller class,but with that approach,the exceptions can be handle only in that particular controller class and if any other controller class throws the same exception than it will not be handled and user will again get the same default exception page.

So a proper approach should be to make this exception method set as globally so that if any such exception occurs in our entire Application that the exception methods defined to handle it at one place should be able to handle it.

In Spring MVC this can be achieved by adding another class and moving all such exception handler method at that one location

In our example we have defined GlobalExceptionHandlerMethods.java 

@ControllerAdvice is the annotation that we need to place on top of this class and add the necessary import statement.

Then move all the exception methods that we want to define globally in this class as below


Just by doing this ,we will be remove all the redundant  methods at one location and would be able to hand those exception globally.

Another way to achieve the same is by making changes in our spring-dispatcher-servlet.xml


The above changes in spring-dispatcher-servlet.xml will do exactly the same as GlobalExceptionHandlerMethods.java  and this  file will not be needed in that case

A Developer can choose any of the above two approach.


Comments are closed