在我毕业的第一年过程中,底层数据交互的对象一般都是自己的DB,基本上没有从第三方获取过数据,所以也没有封装过这部分的工具类。直到前段时间,新增的应用中需要大量获取三方数据,基本上没有DB发挥的余地
最初是通过try catch 的普遍写法进行code,但是写久了之后就发现,每回都需要写try catch等异常捕获的代码,显得代码很冗余,也很费时费事,例如下面的代码
public void test(InDTO inDto) {
if (Objects.isNull(inDto)) {
throw new FxException(NOT_NULL_VALID);
}
ParamInDTO request = buildReqParam(inDto);
Result result = new Result<>();
try {
//三方调用
result = testService.test(request);
if (!result.isSuccess()) {
log.error("test" + result.getMessage();
throw new Exception(HSF_FAIL_UN_CHOICE_PRODUCT, result.getMessage());
}
} catch (Throwable throwable) {
log.error("test" + result.getMessage();
throw new FxException(HSF_FAIL_UN_CHOICE_PRODUCT , throwable , result.getMessage());
}
}
上面的代码写一次还好,两次也还行,三次有点冗余了。到最后应用中到处都是tra catch和异常日志,严重影响美观和代码的规范。对于上述代码,可以把三方调用作为抽象点进行抽离形成一个工具类
@Slf4j
public class WrapperUtil {
public static R doWrapper(Supplier doFun, Object inParam) {
R result = null;
try {
result = doFun.get();
if (Objects.isNull(result)) {
log.error("WrapperUtil.doWrapper, result is null , inParam={}", JSON.toJSONString(inParam));
//自定义业务异常
throw new FxException(ErrorCodeEnum.WRAPPER_HANDLE_FAIL_RESULT_EMPTY);
}
} catch (Throwable throwable) {
log.error("WrapperUtil.doWrapper, result is exception , inParam={} , result={} , throwable={}",
JSON.toJSONString(inParam), JSON.toJSONString(result), JSON.toJSONString(throwable));
boolean needRetry = throwable instanceof HSFTimeOutException;
throw new FxException(ErrorCodeEnum.WRAPPER_HANDLE_FAIL, throwable, needRetry);
}
return result;
}
public static R doWrapper(Supplier doFun, Object inParam, ErrorCodeEnum errorCodeEnum) {
R result = null;
try {
result = doFun.get();
if (Objects.isNull(result)) {
log.error("WrapperUtil.doWrapper, result is null , inParam={}", JSON.toJSONString(inParam));
//自定义业务异常
throw new FxException(errorCodeEnum);
}
} catch (Throwable throwable) {
log.error("WrapperUtil.doWrapper, result is exception , inParam={} , result={} , throwable={}",
JSON.toJSONString(inParam), JSON.toJSONString(result), JSON.toJSONString(throwable));
boolean needRetry = throwable instanceof HSFTimeOutException;
throw new FxException(errorCodeEnum, throwable, needRetry);
}
return result;
}
public static void doWrapperValid(boolean isFail, String errorMsg, ErrorCodeEnum errorCodeEnum, Object inParam, Object outParam) {
if (isFail) {
log.error(errorMsg, inParam.toString(), outParam.toString());
throw new FxException(errorCodeEnum);
}
}
}
public void testWrapperUtil(InDTO inDto){
ValidUtil.notNull(inDto);
ParamInDTO request = buildReqParam(inDto);
Result result = WrapperUtil.doWrapper(() -> testService.test(request), request);
WrapperUtil.doWrapperValid(result.isFail(), "查询XXX失败", ErrorCodeEnum.USER_ROLE_DELETE_ERROR, inDto, result);
});
}