以maven子模块的方式搭建java
<groupId>cn.theviper</groupId> <artifactId>dubbo-exception</artifactId> <packaging>pom</packaging> <version>1.0</version> <modules> <module>api</module> <module>server</module> </modules>
api部分git
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; } ... }
一般咱们会定义一系列业务错误码spring
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,怎么办呢?api
spring aop
加强里面有一个抛出异常加强,用它来转发
一下code和msg就好了maven
server加入依赖gitlab
<dependencies> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.9</version> </dependency> </dependencies>
server定义切面this
@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配置.net
<aop:aspectj-autoproxy/>
能够看到,切面就是拦截了ServiceException,把ServiceException里面的code,msg又传给APIException了code
错误码
放在server带来一个新的问题,api的返回结果每每会用到这个错误码
,怎么办呢?
用继承就行了orm
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异常处理