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 given exception is thrown.
First you need to create a class and put the annotation @ ControllerAdvice . This annotation is used to define methods @ExceptionHandler
, @InitBinder
and @ModelAttribute
that apply to all methods annotated 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;
}
}
No @ExceptionHandler
you pass which Exception class that method will intercept in the controllers.
The advantage is that you do not 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 standard error page for example.
This approach does not catch 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 @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 AOP you can intercept the exceptions that occur in a particular package. If you do not know AOP I recommend reading the documentation .
Sources:
link
link