views:

1526

answers:

2

I was hoping to implement a single "ExceptionController" to handle exceptions that are thrown in execution of my other controllers' methods. I hadn't specified any HandlerExceptionResolver in my application context so according to the API documentation the AnnotationMethodHandlerExceptionResolver should be started. Verified as such in the source. So I am curious to know why the following isn't working.

@Controller
public class ExceptionController {

  @ExceptionHandler(NullPointerException.class)
  public ModelAndView handleNullPointerException(NullPointerException ex) {
    // Do some stuff
    log.error(logging stuff)
    return myModelAndView;
  }
}

@Controller
public class AnotherController {

  @RequestMapping(value="/nullpointerpath")
  public String throwNullPointer() {
    throw new NullPointerException();
  }
}

I see in the debug logs that the three default exception handlers are asked for handling of the exception, but nothing is done and I see "DispatcherServlet - Could not complete request". Followed by the user being displayed the stacktrace and a 500 Internal error.

A: 

I don't think this is a good design. Controllers in Spring handle HTTP requests and map to URLs. I don't think "exception" fits into either bin. It feels like a misuse of Spring to me.

An exception is not an HTTP request. You don't map an exception to a URL. Therefore I'd conclude that controllers aren't intended to be treated as exception handlers.

Controllers are a part of the Spring API, but your design isn't using them as intended, so that's why it's not working. Re-think your design.

duffymo
It's apart of the spring API. Not sure I understand why that it would be misuse then. http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-exceptionhandlers
predhme
+1  A: 

Make sure your Exception handler is returning a view that exists/maps to a handler.

suihock
That seemed to be the issue.
predhme
@predhme, did that really fix your problem? I have an example just like yours, and the @ExceptionHandler method is only invoked when the exception is thrown from the same controller.
colbeerhey
I noticed that later on as well. I guess the most important thing was for me to setup a 500 and 404 pages so that if there was anything I didn't catch, the user wasn't presented with a stack trace.
predhme