package com.ly.mp.cmc.common.aop;
import java.lang.reflect.Method;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
/**
* @author ly-zhangjiaj
* @date 2017年6月3日
*
*/
@Component
@Aspect
public class ExceptionAspect {
@SuppressWarnings("rawtypes")
// @Around(value = "execution(* com.ly.mp.cmc.*.service.**.* (..)) || @annotation(ServiceMethod)")
@Around(value = "execution(* com.ly.mp.cmc.*.service.**.* (..))")
public Object around(ProceedingJoinPoint point) {
Method targetMethod = null;
Logger logger = null;
String classMethod = null;
String loggerMsg = null;
try {
targetMethod = ((MethodSignature) point.getSignature()).getMethod();// 获取捕获方法
Class declaringClass = targetMethod.getDeclaringClass();// 获取捕获方法的所属类
logger = LoggerFactory.getLogger(declaringClass);
classMethod = declaringClass.getName() + "." + targetMethod.getName();
loggerMsg = classMethod;
// logger.error(classMethod);
return point.proceed();
} catch (Throwable e) {
Object obj = null;
try {
String returnMsg = "";
String throwMsg = e.getMessage();
String errorTime = String.valueOf(System.currentTimeMillis());// 记录错误出现的系统毫秒数
if (throwMsg != null && throwMsg.contains("异常信息:")) {// && e instanceof RuntimeException
if (targetMethod.isAnnotationPresent(ServiceMethod.class)) {
returnMsg = targetMethod.getAnnotation(ServiceMethod.class).cnName();
}
returnMsg += "出错:" + throwMsg.replace("异常信息:", "");
loggerMsg += "|" + returnMsg + "|" + errorTime;
} else if (targetMethod.isAnnotationPresent(ServiceMethod.class)) {
returnMsg = targetMethod.getAnnotation(ServiceMethod.class).cnName() + "出错:未知错误(" + errorTime + ")";
loggerMsg += "|" + returnMsg + "|" + errorTime;
} else {
returnMsg = "未知错误(" + errorTime + ")";
loggerMsg += "|" + returnMsg;
}
logger.error(loggerMsg, e);
Class<?> returnType = targetMethod.getReturnType();// 获取捕获方法的返回类型
obj = returnType.newInstance();
Method setMsg = returnType.getMethod("setMsg", String.class);
Method setResult = returnType.getMethod("setResult", String.class);
setMsg.invoke(obj, returnMsg);// 设置返回结果信息
setResult.invoke(obj, "0");// 设置返回结果代码 0代表失败
return obj;
} catch (Exception e1) {
logger.error(loggerMsg + "|切面捕获异常返回类型错误", e1);
return obj;
}
}
}
// @PostConstruct //一加载这个类就是执行这个方法
// public void init()
// {
// int i= 0;
// int j=i;
// }
// @Before(value = "execution(* com.ly.mp.cmc.*.service.**.* (..))") // 方法调用之前
public void start(JoinPoint point) {
System.out.println(
"@Before:目标方法为:" + point.getSignature().getDeclaringTypeName() + "." + point.getSignature().getName());
throw new RuntimeException(
"@Before:目标方法为:" + point.getSignature().getDeclaringTypeName() + "." + point.getSignature().getName());
}
}
AOP异常处理
最新推荐文章于 2024-07-10 11:25:38 发布