`
zhaoyanfangeye
  • 浏览: 122707 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

使用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都是自定义异常类
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics