Spring AOP之异常转换

Spring-AOP之异常转换

引子

最近项目遇到了一个问题,就是说业务层向展现层需要转换成统一个异常类,并抛出异常,但是由于业务层的异常类过多,所以导致业务异常转换代码充斥着异常转换的代码,本着程序猿能省写代码就省写代码的原则,决定用Spring AOP来做一个切片,业务异常类转换.

最原始代码

最原始的代码,咱简称V1.0

 @Override
    public GnAreaVo selectByID(GnAreaCondition condition) throws CallerException {
        try {
            //业务处理
            if (StringUtils.isEmpty(condition.getAreaCode()))
                throw new BusinessException("10001", "区域编码不能为空");
            Gson gson = new Gson();
            //处理结果
            return gson.fromJson(gson.toJson(iGnAreaBusinessService.selectByID(condition.getAreaCode())), GnAreaVo.class);
        } catch (BusinessException ex) {
            //
            throw new CallerException("100001", ex.getErrorMessage());
        } catch (SystemException ex) {
            //
            throw new CallerException("100001", ex.getMessage());
        } catch (Exception ex) {
            //
            throw new CallerException("10001", "系统异常");
        }
    }

升级版本

升级版本,简称V1.1,提取出一个公共类来处理

@Override
    public GnAreaVo selectByID(GnAreaCondition condition) throws CallerException {
        try {
            //业务处理
            if (StringUtils.isEmpty(condition.getAreaCode()))
                throw new BusinessException("10001", "区域编码不能为空");
            Gson gson = new Gson();
            //处理结果
            return gson.fromJson(gson.toJson(iGnAreaBusinessService.selectByID(condition.getAreaCode())), GnAreaVo.class);
        } catch (BusinessException ex) {
            //
            throw DubboExceptAssembler.assemble(ex);
        } catch (SystemException ex) {
            //
            throw DubboExceptAssembler.assemble(ex);
        } catch (Exception ex) {
            //
            throw DubboExceptAssembler.assemble(ex);
        }
    }

最终版

代码更加简单了,并且能支持更加多异常类的转换,减少业务程序的无用代码,下面来看看怎么实现的。
首先写一个AOP

import com.ai.runner.base.exception.BusinessException;
import com.ai.runner.base.exception.SystemException;
import com.ai.runner.utils.util.DubboExceptAssembler;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.aspectj.lang.JoinPoint;

public class DubboExceptionConvertInterceptor {

    private static final Logger logger = LogManager.getLogger(DubboExceptionConvertInterceptor.class);

    public void convertException(JoinPoint joinPoint, Exception error) {
        logger.error("执行{}类中的{}方法出错,出错原因:{}", joinPoint.getTarget().getClass().getName(),
                joinPoint.getSignature().getName());
        if (error instanceof SystemException) {
            throw DubboExceptAssembler.assemble((SystemException) error);
        }
        if (error instanceof BusinessException) {
            throw DubboExceptAssembler.assemble((BusinessException) error);
        }
        throw DubboExceptAssembler.assemble(error);
    }
}

Spring的配置:

<bean id="dubboExceptionConvertor" class="DubboExceptionConvertInterceptor"/>

    <aop:config>
        <aop:aspect id="aspectLoggging" ref="dubboExceptionConvertor">
            <aop:pointcut id="dubboExceptionThrowing"
                          expression="execution (* com.ai.runner.center.common.api.*.impl.*.*(..))"/>
            <aop:after-throwing method="convertException" throwing="error"
                                pointcut-ref="dubboExceptionThrowing"/>
        </aop:aspect>
    </aop:config>

业务代码:

  @Override
    public GnAreaVo selectByID(GnAreaCondition condition) throws CallerException {
        if (StringUtils.isEmpty(condition.getAreaCode()))
            throw new BusinessException("10001", "区域编码不能为空");
        Gson gson = new Gson();
        return gson.fromJson(gson.toJson(iGnAreaBusinessService.selectByID(condition.getAreaCode())), GnAreaVo.class);
    }

Done!

时间: 2024-08-14 09:14:53

Spring AOP之异常转换的相关文章

Spring aop 实现异常拦截

使用aop异常挂载功能可以统一处理方法抛出的异常,减少很多重复代码,实现如下: 1.实现ThrowAdvice 1 public class ExceptionHandler implements ThrowsAdvice { 2 3 private static Logger LOGGER = LoggerFactory.getLogger(ExceptionHandler.class); 4 5 public void afterThrowing(Exception e) throws Th

Spring学习(二十五)Spring AOP之增强介绍

课程概要: Spring AOP的基本概念 Spring AOP的增强类型 Spring AOP的前置增强 Spring AOP的后置增强 Spring AOP的环绕增强 Spring AOP的异常抛出增强 Spring AOP的引介增强 一.Spring AOP增强的基本概念 Spring当中的专业术语-advice,翻译成中文就是增强的意思. 所谓增强,其实就是向各个程序内部注入一些逻辑代码从而增强原有程序的功能. 二.Spring AOP的增强类型 首先先了解一下增强接口的继承关系 如上图

Spring AOP操作action时无法注入,报NullPointer异常

Spring AOP操作action时无法注入,报NullPointer异常当使用Spring AOP对action层进行操作时,会出现注入失败的问题,出现空指针异常.原因是一般struts2+spring应用中,spring的插件只负责为action的ioc部分,但并没有进行功能加强,即采用代理的机制,所有的action还是使用struts2进行管理,在使用AOP后,这些action需要由spring进行管理,如果没有由spring进行代理,将出现注入失败.解决办法:Struts2的一个特殊的

spring aop(四)

直接找到解析aop标签的方法: 1 protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) { 2 if (delegate.isDefaultNamespace(root)) { 3 NodeList nl = root.getChildNodes(); 4 for (int i = 0; i < nl.getLength(); i++) { 5 Node node = n

Spring AOP详解 、 JDK动态代理、CGLib动态代理

AOP是Aspect Oriented Programing的简称,面向切面编程.AOP适合于那些具有横切逻辑的应用:如性能监测,访问控制,事务管理以及日志记录.AOP将这些分散在各个业务逻辑中的代码通过横向切割的方式抽取到一个独立的模块中. 一.AOP术语 1.连接点(Joinpoint) 程序执行的某个特定位置:如类开始初始化之前.类初始化之后.类某个方法调用前.调用后等:一个类或一段程序代码拥有一些具有边界性质的特定点,这些代码中的特定点就成为“连接点”,Spring仅支持方法的连接点,即

(转)利用Spring AOP自定义注解解决日志和签名校验

一.需解决的问题 部分API有签名参数(signature),Passport首先对签名进行校验,校验通过才会执行实现方法. 第一种实现方式(Origin):在需要签名校验的接口里写校验的代码,例如: boolean isValid = accountService.validSignature(appid, signature, client_signature); if (!isValid) return ErrorUtil.buildError(ErrorUtil.ERR_CODE_COM

利用Spring AOP自定义注解解决日志和签名校验

转载:http://www.cnblogs.com/shipengzhi/articles/2716004.html 一.需解决的问题 部分API有签名参数(signature),Passport首先对签名进行校验,校验通过才会执行实现方法. 第一种实现方式(Origin):在需要签名校验的接口里写校验的代码,例如: boolean isValid = accountService.validSignature(appid, signature, client_signature); if (!

Spring AOP: Spring之面向方面编程

Spring AOP: Spring之面向方面编程 面向方面编程 (AOP) 提供从另一个角度来考虑程序结构以完善面向对象编程(OOP). 面向对象将应用程序分解成 各个层次的对象,而AOP将程序分解成各个方面 或者说 关注点 . 这使得可以模块化诸如事务管理等这些横切多个对象的关注点.(这些关注点术语称作 横切关注点.) Spring的一个关键组件就是AOP框架. Spring IoC容器(BeanFactory 和ApplicationContext)并不依赖于AOP, 这意味着如果你不需要

【转载】Spring AOP详解 、 JDK动态代理、CGLib动态代理

原文地址:https://www.cnblogs.com/kukudelaomao/p/5897893.html AOP是Aspect Oriented Programing的简称,面向切面编程.AOP适合于那些具有横切逻辑的应用:如性能监测,访问控制,事务管理以及日志记录.AOP将这些分散在各个业务逻辑中的代码通过横向切割的方式抽取到一个独立的模块中. 一.AOP术语 1.连接点(Joinpoint) 程序执行的某个特定位置:如类开始初始化之前.类初始化之后.类某个方法调用前.调用后等:一个类