接口定义规范

同一个接口,有时候返回数组,有时候返回单个;成功的时候返回对象,失败的时候返回错误信息字符串。工作中有个系统集成就是这样定义的接口,真是辣眼睛。这个对应代码上,返回的类型是map,json,object,都是不应该的。实际工作中,我们会定义一个统一的格式,就是ResultBean,分页的有另外一个PageResultBean


@Slf4j
public class ControllerAop {

public Object handlerControllerMethod(MethodInvocationProceedingJoinPoint methodInvocationProceedingJoinPoint){
long startTime = System.currentTimeMillis();
ResultBean<?> resultBean;
try {
resultBean = (ResultBean<?>)methodInvocationProceedingJoinPoint.proceed();
} catch (Throwable throwable) {
resultBean = handlerException(methodInvocationProceedingJoinPoint,throwable);
throwable.printStackTrace();
}
return resultBean;
}

private ResultBean<?> handlerException(MethodInvocationProceedingJoinPoint methodInvocationProceedingJoinPoint,Throwable e){
ResultBean<?> resultBean = new ResultBean<>();
if(e instanceof CheckException){
resultBean.setMsg(e.getLocalizedMessage());
resultBean.setCode(ResultBean.FAIL);
}else{
log.error(methodInvocationProceedingJoinPoint.getSignature()+" error ",e);
resultBean.setMsg(e.toString());
resultBean.setCode(ResultBean.FAIL);
//未知异常是应该关注的重点,这里可以做其他操作,如通知邮件,单独写到某个文件等等。
}
return resultBean;
}

}

统一的接口规范,能帮忙规避很多无用的返工修改和可能出现的问题。能使代码可读性更加好,利于进行aop和自动化测试这些额外工作。大家一定要重视。

 原文链接:https://zhuanlan.zhihu.com/p/28708259

原文地址:https://www.cnblogs.com/shareTechnologyl/p/11713422.html