@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都是自定义异常类