import java.util.Arrays;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import lombok.extern.slf4j.Slf4j;
@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都是自定义异常类
本文介绍了一种利用AOP技术处理服务层异常的方法。通过@Aspect注解定义切面,并使用@Around注解实现环绕通知,对指定包下的服务实现类进行增强。该方法能够捕获并统一处理包括参数异常、并发异常在内的多种异常类型。

2万+

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



