package org.example.interc;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ServiceInterceptor implements MethodInterceptor {
private Logger logger = LoggerFactory.getLogger(this.getClass());
public ServiceInterceptor() {
}
public Object invoke(MethodInvocation invocation) throws Throwable {
long startTimeMillis = System.currentTimeMillis();
long endTimeMillis = 0L;
String className = invocation.getThis().getClass().getSimpleName();
String interfaceFullName = invocation.getThis().getClass().getName();
String methodName = invocation.getMethod().getName();
String txName = "交易:" + className + "." + methodName;
try {
Class<?>[] interfaces = invocation.getThis().getClass().getInterfaces();
if (interfaces != null && interfaces.length > 0) {
interfaceFullName = interfaces[0].getName();
}
} catch (Exception var15) {
this.logger.warn("获取接口名称异常", var15);
}
Object[] args = invocation.getArguments();
boolean noArgs = false;
if (args == null || args.length < 1 || args[0] == null) {
noArgs = true;
}
try {
if (!noArgs) {
CheckInputUtil.validate(args[0]);
}
Object returnObj = invocation.proceed();
endTimeMillis = System.currentTimeMillis();
this.logger.info(txName + " success ,耗时:" + (endTimeMillis - startTimeMillis) + "ms");
return returnObj;
} catch (Exception var16) {
endTimeMillis = System.currentTimeMillis();
if (var16 instanceof ServiceException) {
ServiceException serE = (ServiceException) var16;
if (StringUtils.length(serE.getCode()) < 10) {
this.logger.error("业务异常:" + serE.getExtMsg(), serE);
this.logger.info(txName + " failure ,耗时:" + (endTimeMillis - startTimeMillis) + "ms");
} else {
String logLevel = serE.getCode().substring(5, 6);
if ("E".equals(logLevel)) {
this.logger.error("业务异常:" + serE.getExtMsg(), serE);
this.logger.info(txName + " failure ,耗时:" + (endTimeMillis - startTimeMillis) + "ms");
} else i
Springboot使用MethodInterceptor和切面统一打印service层信息
最新推荐文章于 2024-05-29 21:56:36 发布
该博客介绍了如何使用Spring AOP和AspectJ表达式来定义一个切点,通过`ServiceInterceptor`方法拦截器捕获并处理服务层异常。当发生异常时,根据异常类型和错误代码进行不同级别的日志记录,包括业务异常、警告和错误信息,并提供了自定义的`ServiceException`来封装异常信息。

2566

被折叠的 条评论
为什么被折叠?



