在日常开发的时候,有时候会出错,这个时候如果去看日志,会有一大堆日志查找很困难,所以就用spring的Aop来捕捉异常,存进数据库
切入点
加上一些信息,方便更加快速定位错误信息
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
@Documented
public @interface LogAnnotation {
/**
* 模块
*/
public String title() default " ";
/**
* 功能
*/
public BusinessType businessTyp() default BusinessType.INSERT;
}
@Aspect
@Component
public class LogExceptionAspectj extends RuntimeException{
@Autowired
private ExceptionHandleService exceptionHandleService;
@AfterThrowing(value = "@annotation(com.twoblog.twoblogmaster.annotation.LogAnnotation)",throwing = "e")
public void exceptionHandle(JoinPoint joinPoint,Exception e){
//获取异常类型
String exceptionType = e.getClass().getName();
//获取异常信息
String message = ExceptionUtil.getMessage(e);
//获取异常的参数
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
LogAnnotation annotation = signature.getMethod().getAnnotation(LogAnnotation.class);
BusinessType businessType = annotation.businessTyp();
String s = businessType.toString();
String title = annotation.title();
//获取到出错的路径
String errorPath = joinPoint.getTarget().getClass().getName()+"."+signature.getName();
ExceptionHandle build = ExceptionHandle.builder().message(message).methodTitle(title).methodFunction(s).exceptionType(exceptionType).exceptionPath(errorPath).build();
exceptionHandleService.save(build);
}
}