How to catch non-MVC and non-REST exceptions in Spring Boot
You can define an aspect.Using Java-based configuration it will look like this:
@Aspectpublic class ExceptionHandler { @AfterThrowing(pointcut="execution(* your.base.package..*.*(..))", throwing="ex") public void handleError(Exception ex) { //handling the exception }}
If you need to inject a bean, add the @Component
annotation:
@Aspect@Componentpublic class ExceptionHandler { @Autowired private NotificationService notificationService; @AfterThrowing(pointcut="execution(* your.base.package..*.*(..))", throwing="ex") public void handleError(Exception ex) { notificationService.sendMessage(ex.getMessage()); }}
You can use the aop in spirngframework,first you should config the aop configuration.
<bean id="aspect" class="com.zhuyiren.Main"/><aop:config> <aop:aspect ref="aspect"> <aop:after-throwing method="after" throwing="ex" pointcut="execution(* com.zhuyiren.service..*.*(..)),args(ex)"/> </aop:aspect></aop:config>
and then you should declare a aspect
class has method be named after
:
public class Main {public void after(JoinPoint point,Throwable ex){ System.out.println(point); System.out.println("catch error:"+ex.getMessage());}
When the service is throwning a error,the method will catch and resolve it.In my Sevice,i make a ArithmeticException,and run the application,the print is:
execution(TeacherInfo com.zhuyiren.service.TeacherService.getTeacherInfo())catch error:/ by zero
Of course,the above configuration is depends on xml,you also can do it through Annotation
such as @Aspect
,@Pointcut
,@AfterThrowing
.