My Spring MVC app is full of methods that look like this:
@RequestMapping(value = "/foo", method = RequestMethod.GET)
public final void foo(HttpServletRequest request, ModelMap modelMap){
try{
this.fooService.foo();
}
catch (Exception e){
log.warn(e.getMessage(), e);
}
}
Exceptions are caught and logged but not handled otherwise.
The fooService called above does the same thing, never throwing exceptions up to the controller but catching and logging them. So, actually this controller exception code will never get invoked.
What’s the best and simplest approach to implement proper exception handling in my app?
Get rid of all
catchstatements if all they do is logging carelessly.catchis meant to handle the error, not hide it.Once all these catches are removed, install one global exception resolver in Spring MVC (1, 2, 3, …) Simply implement this trivial interface:
In your exception resolver you might simply log the exception once and let it go as unprocessed (return
null), so that error mappings inweb.xmlwill forward request to proper error page. Or you can handle exception yourself and render some error page. AFAIK in simplest case there is no need for register exception resolver, just define it as a Spring bean/annotate with@Service.Remember, catch the exception only when you know what to do with. Logging is only for troubleshooting, it doesn’t handle anything.
BTW this:
is not only a very poor exception handling, but it is also slightly incorrect. If your exception does not have a message, you will see mysterious
nulljust before the stack trace. If it does, the message will appear twice (tested with Logback):…sometimes undesirable, especially when exception message is very long.
UPDATE: When writing your own exception logger consider implementing both
org.springframework.web.servlet.HandlerExceptionResolverandorg.springframework.core.Ordered. ThegetOrder()should return something small (like0) so that your handler takes precedence over built-in handlers.It just happened to me that
org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolverrunning prior to my handler returned HTTP 500 without logging the exception.