最佳实践:使用Spring AOP对异常进行统一处理(4)
时间:2025-07-10
时间:2025-07-10
有必要使用一个统一的异常处理机制 来进行某些异常处理的统一决策。比如对异常进行统一的日志记录,对散落在各处的某类异常进行统一处理等。
public void setNoCatchedExceptions(Set<String> noCatchedExceptions){
this.noCatchedExceptions = noCatchedExceptions;
}
/**
*捕获异常记录日志.
*@param joinPoint 连接点,可通过连接点获取目标对象,目标方法签名,及方法参数 *@param ex 捕获的异常
*/
public void log(JoinPoint joinPoint, Throwable ex) {
/* 过滤不记录日志的异常*/
for(String exClassName:noCatchedExceptions){
try {
Class clazz = Class.forName(exClassName.trim());
if (clazz.isAssignableFrom(ex.getClass()))
return;
} catch (ClassNotFoundException e1) {
logger.error("applicationContext-exception: propertity
noCatchedExceptions setting error:", e1);
}
}
List<Object> args
=java.util.Arrays.asList(joinPoint.getArgs());
String strArgs = args.toString();
Object[] objs = new Object[]{ joinPoint.getSignature().getName(),
strArgs.substring(0, strArgs.length() -1).substring(1) };
String message = "{}({}) execute error!!";
StringBuffer buf = new StringBuffer(message)
.append("\r\nStackTrace:")
.append(ExceptionUtil.bufferExceptionTrace(ex));
logger.error(buf.toString(), objs);
}
}
/**
* 未处理的异常在此进行统一处理,此通在最后执行.
*
* @author yrliang
*
*/
@SuppressWarnings("unchecked")
public class ExceptionMessageTransfer {
private Logger logger = LoggerFactory.getLogger(this.getClass()); private Set<String> noCatchedExceptions = new HashSet<String>();
public Set<String> getNoCatchedExceptions() {
return noCatchedExceptions;
}
public void setNoCatchedExceptions(Set<String> noCatchedExceptions) {
this.noCatchedExceptions = noCatchedExceptions;
}
/**
*捕获异常进行处理
下一篇:钢材市场营运方案