Spring 3 - Create ExceptionHandler for NoSuchRequestHandlingMethodException Spring 3 - Create ExceptionHandler for NoSuchRequestHandlingMethodException spring spring

Spring 3 - Create ExceptionHandler for NoSuchRequestHandlingMethodException


@ExceptionHandler-annotated methods are invoked when a @RequestMapping method on that same class throws an exception. So when you added the mapping which threw the NullPointerException, that worked, since the mapped method and exception handler were together in the same class.

When no mapping is found, Spring has no way of associating the NoSuchRequestHandlingMethodException with your @ExceptionHandler, because it didn't get as far as matching the request to a handler method. This isn't mentioned explicitly in the docs, but is the behaviour I've observed.

If you want to handle this exception specially, you're going to have to use the more general HandlerExceptionResolver approach, rather than the more specialised @ExceptionHandler technique.


In Spring 3.2 you can use @ContollerAdvice to have an ExceptionHandler for all your Controllers like this:

@ControllerAdvicepublic class GeneralHandler {   @ExceptionHandler   public ModelAndView handleException (NoSuchRequestHandlingMethodException ex) {        ModelAndView mav = new ModelAndView();        ...        return mav;   }}

You can even add more annotations to return serialized json

@ExceptionHandler    @ResponseBody    @ResponseStatus(HttpStatus.BAD_REQUEST)    public RestError resolveBindingException ( MethodArgumentNotValidException methodArgumentNotValidException, Locale locale )    {        BindingResult bindingResult = methodArgumentNotValidException.getBindingResult();        return getRestError(bindingResult, locale);    }


You could go with this approach, it is great idea and works, necessity to throw exceptions only withing particular Handler makes @ExceptionHandler not so useful as it looks.