SpringAOP----捕捉异常存进数据库,方便找到问题

本文介绍了如何使用Spring AOP技术配合LogAnnotation注解,实时捕获并记录应用中的异常信息,通过附加模块、功能和路径信息,简化日志查找,提升故障排查效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在日常开发的时候,有时候会出错,这个时候如果去看日志,会有一大堆日志查找很困难,所以就用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);
    }
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值