Using Spring MVC
Spring MVC provides a way to handle exceptions, the annotation @Exceptionhandler . For each controller we can define a method that is called when a certain exception is thrown.
First you need to create a class and place the annotation @Controlleradvice. This annotation is used to define methods @ExceptionHandler
, @InitBinder
and @ModelAttribute
which apply to all methods noted with @RequestMapping
.
@ControllerAdvice
public class SendMailExceptionHandler {
@Autowired
protected SendMailService sendMailService;
@ExceptionHandler(Exception.class)
public ModelAndView exceptionHanlder(Exception ex) {
String mensagem = "Ocorreu um erro no sistema xyz: " + ex.getMessage();
sendMailService.send(mensagem);
ModelAndView mv = new ModelAndView();
mv.addObject("exception", exception);
mv.addObject("url", req.getRequestURL());
mv.setViewName("error");
return mv;
}
}
In the @ExceptionHandler
you pass which class of Exception that method will intercept in controllers.
The advantage is that you don’t need to use try catch
in your controllers and in addition to sending the email the method will redirect the user to a page you want, a default error page for example.
This approach does not capture errors from other calls that do not pass through the controller, for example you have an automatic execution from time to time that ends up generating an exception and in this case the @ExceptionHandler
will not capture.
Using AOP
With Spring, you can write an Interceptor AOP :
@Aspect
public class ErrorInterceptor{
SendMailService sendMailService;
@AfterThrowing(pointcut = "execution(* br.com..* (..))", throwing = "ex")
public void errorInterceptor(Exception ex) {
if (logger.isDebugEnabled()) {
logger.debug("Interceptor inicializado");
}
String mensagem = "Ocorreu um erro no sistema xyz. " + ex.getMessage();
sendMailService.send(mensagem);
if (logger.isDebugEnabled()) {
logger.debug("Interceptor finalizado.");
}
}
}
With the AOP you can intercept the exceptions that occur in a given package. If you do not know AOP recommend reading the documentation.
Sources:
https://stackoverflow.com/questions/10947933/aop-exception-handling
https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc
Don’t do this, unless your system has only one or two users and no heavy processing. If you have anything more than that, you’ll soon burst someone’s email box, the shipping limit, will slow down the system and fill up the bag so much that they will soon disable the process. Depending on how critical the process is, you can select some types of critical errors and place them in a queue or table or even in the logs and keep another scheduled process that collects the information and notifies the responsible party when there is something relevant. Basic errors should be caught in tests.
– utluiz