最佳实践:使用Spring AOP对异常进行统一处理(3)
时间:2025-07-10
时间:2025-07-10
有必要使用一个统一的异常处理机制 来进行某些异常处理的统一决策。比如对异常进行统一的日志记录,对散落在各处的某类异常进行统一处理等。
class = "com.grgbanking.platform.core.exception.handler.ExceptionMessageTransfer">
<property name = "noCatchedExceptions">
<set>
<value>com.grgbanking.platform.core.exception.SysException</value> <value>com.grgbanking.platform.core.exception.AppException</value> <value>com.grgbanking.platform.core.exception.PasswordOverdueException</value> <value>ernameNotFoundException</value>
</set>
</property>
</bean>
<aop:config proxy-target-class="true">
<!—配置切入点: 所有service类方法执行时
<aop:pointcut id="exPointcut1" expression="execution(* com.grgbanking..service.*.*(..))"/>
<!—配置记录异常日志切面-->
<aop:aspect ref="exceptionLog" order="3">
<!—配置抛出异常后通知,通知方法是log, ex是log方法中异常参数的名称--> <aop:after-throwing pointcut-ref="exPointcut1" method="log" throwing="ex"/>
</aop:aspect>
<!—配置异常转换切面,通知方法是handle, ex是handle方法中异常参数的名称-->
<aop:aspect ref=" exceptionTransfer " order="1">
<aop:after-throwing pointcut-ref="exPointcut1" method="handle" throwing="ex"/>
</aop:aspect>
</aop:config>
Spring AOP中具体实现拦截处理的类:
/**
* 拦截系统异常记录日志.
*
* @author yrliang
*
*/
public class ExceptionLogger {
private Logger logger = LoggerFactory.getLogger(this.getClass()); private Set<String> noCatchedExceptions = new HashSet<String>();
public Set<String> getNoCatchedExceptions() {
return noCatchedExceptions;
}
下一篇:钢材市场营运方案