nay
nay

Reputation: 105

ControllerAdvice annotation in spring 4 is not working

In spring-mvc.xml:

<beans ...>
     <mvc:annotation-driven/>
     <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" />
     <bean class="com.app.controllers.ExceptionController"/>
     ....
</beans>

In GlobalException.java:

@ControllerAdvice(basePackages = "com.exceptions")
public class GlobalException {
    @ExceptionHandler(UserDefinedException.class)
    public ModelAndView processCustomException(UserDefinedException ud) {
    ModelAndView mav = new ModelAndView("exceptionPage");
    mav.addObject("name", ud.getName());
    mav.addObject("message", ud.getMessage());
    return mav;
}
}

In ExceptionController.java:

public class ExceptionController implements Controller {
     @Override
     public ModelAndView handleRequest(HttpServletRequest arg0, HttpServletResponse arg1) throws Exception {
     throw new UserDefinedException("Custom Exception has occured", "CustomException");
  }
}

Ecxception is throwing as com.exceptions.UserDefinedException: Custom Exception has occured. But ExceptionHandler method is not called. Whats wrong is this code. I'm using spring 4.3 version.

Upvotes: 0

Views: 1308

Answers (1)

Tommy Brettschneider
Tommy Brettschneider

Reputation: 1490

enable Spring's component scanning in your spring-mvc.xml by adding this:

<context:component-scan base-package="com.exceptions" />

and remove your obsolete XML configured Spring bean (<bean class="com.app.controllers.ExceptionController"/>)

also annotate your controller classes with @Controller and add a @RequestMapping to your controller methods, e.g. like this:

@Controller
public class ExceptionController {

    @RequestMapping(value="/whatever", method=RequestMethod.GET)
    public ModelAndView handleRequest(HttpServletRequest arg0, HttpServletResponse arg1) throws Exception {
       throw new UserDefinedException("Custom Exception has occured", "CustomException");
    }
}

this way, your classes annotated with Spring stereotype annotations (@Component, @Service, @Controller, @Repository) should be found, instantiated and registered as Spring beans by Spring itself at application startup!

Upvotes: 1

Related Questions