以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异常处理


下载


TheViper
465 声望16 粉丝

« 上一篇
spring-boot跨域
下一篇 »
spring-boot上传