使用AOP实现异常处理


@Aspect
public class ServiceExceptionAOPHandler implements Ordered {
private final Logger logger = LoggerFactory.getLogger(getClass());
@Around("execution(* com.gosophia.*.service.impl.*.*(..))")
public Object serviceExceptionIterceptor(ProceedingJoinPoint joinPoint)
throws Throwable {
try {
logger.info("The method " + joinPoint.getSignature().getName()
+ "() begins with " + Arrays.toString(joinPoint.getArgs()));
Object result = joinPoint.proceed();
logger.info("The method " + joinPoint.getSignature().getName()
+ "() ends with " + result);
return result;
} catch (IllegalArgumentException iae) {// 捕获参数异常
StringBuilder sb = new StringBuilder();
sb.append(joinPoint.getTarget().getClass().getName() + " : "
+ Arrays.toString(joinPoint.getArgs()) + " in "
+ joinPoint.getSignature().getName() + "()");
ExceptionDetail detail = new ExceptionDetail();
detail.setErrorCode(ErrorCodeList.PARAMENTER_ERROR_CODE);
throw new ParameterException(sb.toString(), detail, iae);
}
catch (org.hibernate.StaleObjectStateException cfe) {// 捕获数据并发异常
ExceptionDetail ed = new ExceptionDetail();
ed.setErrorCode(ErrorCodeList.CONCURRENCY_ERROR_CODE);
ed.setMessage("detail message show,concurrency exception ");
throw new ConcurrencyException("concurrency exception", ed, cfe);
}
catch (ConcurrencyFailureException cfe) {// 捕获数据并发异常
ExceptionDetail ed = new ExceptionDetail();
ed.setErrorCode(ErrorCodeList.CONCURRENCY_ERROR_CODE);
ed.setMessage("detail message show,concurrency exception ");
throw new ConcurrencyException("concurrency exception", ed, cfe);
} catch (DataAccessException dae) {// 捕获其他数据访问异常,此处如需细化需参考spring
ExceptionDetail ed = new ExceptionDetail();
ed.setErrorCode(ErrorCodeList.CRITICAL_TECHNICAL_ERROR_CODE);
throw new TechnicalException(
"critical data access exception", ed, dae);
}

}
//在applicationContext中使用
<bean id="serviceExceptionHandler"
class="com.gosophia.commons.exception.ServiceExceptionAOPHandler"></bean>

其中
ExceptionDetail,ConcurrencyException和ParameterException都是自定义异常类
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值