AOP实现的统一日志处理

编写一个切面类

package com.**.sale.score.service.aspect;

import com.zhangmen.sale.score.common.Result;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class ExceptionAspect {

    private static final Logger logger = LoggerFactory.getLogger(ExceptionAspect.class);

    @Pointcut("execution(* com.*.sale.score.service.impl.*Impl.*(..))")
    public void pointcut() {
    }

    @Around("pointcut()")
    public Object interceptor(ProceedingJoinPoint proceedingJoinPoint) {
        MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();
        String className = methodSignature.getDeclaringTypeName();
        String methodName = methodSignature.getName();
        Object returnObject;
        try {
            returnObject = proceedingJoinPoint.proceed();
        } catch (Exception e) {
            if (e instanceof DuplicateKeyException) {
                logger.error("call {},系统异常-DuplicateKeyException异常:{}", methodName, e);
                throw (DuplicateKeyException) e;
            }
            if (e instanceof ArithmeticException) {
                logger.error("call {},系统异常-ArithmeticException异常:{}", methodName, e);
                throw (ArithmeticException) e;
            }
            if (e instanceof BusinessException) {
                logger.error("call {},自定义异常-BusinessException异常:{}", methodName, e);
                return Result.failure(e.getMessage());
            }
            logger.error("call {},系统异常-其他异常:{}", methodName, e);
            throw new RuntimeException(e);
        } catch (Throwable e) {
            logger.error("call {},系统异常:{}", methodName, e);
            throw new RuntimeException(e);
        }
        return returnObject;

    }



}

可以捕获自己定义的异常

package com.**.sale.score.service.aspect;/**

/**
 *@ClassName BusinessException
 *@Description 自定义异常,全局捕获
 *@Author wangwei
 *@Date 2019/10/16 10:27
 *@Version V1.0
 **/
public class BusinessException extends RuntimeException  {
    public BusinessException(String message) {
        super(message);
    }
}

 

上一篇:AspectJ框架中的切入点表达式


下一篇:Spring 3.0 / AOP / Aspectj:autoproxy拦截对getConnection()的任何调用