以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異常處理