Thursday, February 7, 2008

How to catch those unwanted and uncaught exceptions before they reach the user

Users of your applications certainly don't want to see any cryptic Java exception messages and stack traces. So, how do you catch and process all uncaught exceptions before they reach some level in stack, e.g. before the user interface in a web application? This can be troublesome when you don't have a single entry-point from web interface to service layer.

Well, one way you can do it, is to leverage AspectJ.

@Aspect
public class ErrorsAspect {
@AfterThrowing(pointcut = "execution(public * com.example.your.package..*Controller.*(..))", throwing = "t")
public void handleUserVisibleException(Throwable t) {
.. log ..
.. send mail ..
.. etc ..
}
}

This kind of advice re-raises the exception after it's done, so you might want to use an Around advice and catch the exception if you don't want it to progress. Remember that you can write more complex pointcuts when you need information on target objects or function arguments.

However, if you want to output a pretty error screen to the user and you use Spring MVC as your web framework, then just implement the HandlerExceptionResolver interface (it can be as simple as a one-liner) or use the provided SimpleMappingExceptionResolver.

No comments: