抛出dubbo中的异常

以maven子模块的方式搭建

    <groupId>cn.theviper</groupId>
    <artifactId>dubbo-exception</artifactId>
    <packaging>pom</packaging>
    <version>1.0</version>

    <modules>
        <module>api</module>
        <module>server</module>
    </modules>

api部分

public class APIException extends RuntimeException implements Serializable{

    public int code;
    public String msg;

    public APIException(String msg) {
        super(msg);
    }

    public APIException(int code, String msg) {
        super(msg);
        this.code = code;
        this.msg = msg;
    }
    ...
}

通常我们会定义一系列业务错误码

public enum APICode {

    OK(Integer.valueOf(0), "success"),
    PARAM_INVALID(4100, "parameter invalid");

    private int code;
    private String msg;

    APICode(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    getter setter...

}

错误码是放在server还是api好呢?
当然是放在server好呢,因为不用每次一修改业务错误码,就要更新api版本,但是api又不能反过来依赖server,怎么办呢?

spring aop

spring aop增强里面有一个抛出异常增强,用它来转发一下code和msg就行了

  • server加入依赖

<dependencies>
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.8.9</version>
    </dependency>
</dependencies>
  • server定义切面

@Component
@Aspect
public class ServiceExceptionInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(ServiceExceptionInterceptor.class);

    @AfterThrowing(throwing="ex",pointcut="execution(* cn.theviper.service.**.*(..))")
    public APIResult handle(ServiceException ex){
        logger.info("intercept ServiceException:{}",ex.toString());
        throw new APIException(ex.getCode(),ex.getMsg());
    }

}
  • spring配置

<aop:aspectj-autoproxy/>

可以看到,切面就是拦截了ServiceException,把ServiceException里面的code,msg又传给APIException了

返回的结果

错误码放在server带来一个新的问题,api的返回结果往往会用到这个错误码,怎么办呢?
用继承就好了

  • api

    APIResult register(RegisterForm form) throws APIException;
public class APIResult<T> implements Serializable{

    public int code;
    public T data;
    public String msg;

    public APIResult() {
    }
    ...

}
  • server

public class ServerResult<T> extends APIResult<T>{

    public ServerResult() {
    }

    public ServerResult(APICode apiCode){
        this.code=apiCode.getCode();
        this.msg=apiCode.getMsg();
    }

    public ServerResult setData(T data){
        super.data=data;
        return this;
    }

}

返回的时候,直接

return new ServerResult(APICode.OK).setData("callback msg");

关于dubbo的异常分析,可以参见浅谈dubbo的ExceptionFilter异常处理


下载

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值