在工作中使用Feign调用别的服务时,有时需要获取异常情况下对方服务所报的完整的异常信息,记录流程方便查看
- 首先对调用对方服务的代码进行catch:
try {
XxxResult result = XxxFeignClient.xxx(Req);
} catch (FeignException.FeignClientException ex) {
//这里捕获的异常信息使用FeignException.FeignClientException接收
- 获取到feign传过来的异常信息数据流
ByteBuffer byteBuffer = ex.responseBody().get();
Charset charset = Charset.forName("utf-8");
- 将数据流信息转成string
String json = charset.decode(byteBuffer).toString();
- 将string转成json格式
JSONObject resultData = JSONObject.parseObject(json);
- 打印出返回过来的异常信息
log.info("异常信息为===========>----{}", resultData);
- 处理异常信息并将异常信息再次封装
if ("10314".equals(resultData.getString("error"))){
exceptionData.setError(ResponseEnum.INVALID_TEMP_TOKEN.getName());
exceptionData.setError_description(ResponseEnum.INVALID_TEMP_TOKEN.getIntroduction());
}else if ("10303".equals(resultData.getString("error"))){
exceptionData.setError(ResponseEnum.INVALID_TOKEN.getName());
exceptionData.setError_description(ResponseEnum.INVALID_TOKEN.getIntroduction());
}
return new Result(exceptionData, Result.RESOURCE_NOT_FOUND, Result.ERROR, requestId);
}
完整的代码流程如下:
try {
XxxResult result = XxxFeignClient.xxx(Req);
} catch (FeignException.FeignClientException ex) {
log.info("===========>----{}", ex);
//获取到feign传过来的异常信息为数据流
ByteBuffer byteBuffer = ex.responseBody().get();
Charset charset = Charset.forName("utf-8");
//将数据流信息转成string
String json = charset.decode(byteBuffer).toString();
//将string转成json格式
JSONObject resultData = JSONObject.parseObject(json);
//打印出返回给我的异常信息
log.info("异常信息为===========>----{}", resultData);
//将异常信息再次封装
if ("10314".equals(resultData.getString("error"))){
exceptionData.setError(ResponseEnum.INVALID_TEMP_TOKEN.getName());
exceptionData.setError_description(ResponseEnum.INVALID_TEMP_TOKEN.getIntroduction());
}else if ("10303".equals(resultData.getString("error"))){
exceptionData.setError(ResponseEnum.INVALID_TOKEN.getName());
exceptionData.setError_description(ResponseEnum.INVALID_TOKEN.getIntroduction());
}
return new Result(exceptionData, Result.RESOURCE_NOT_FOUND, Result.ERROR, requestId);
}
逻辑流程为主要参考内容,由于经验不足,代码写的不够规范,仅供逻辑参考,若有不足还请指出,互相进步,感谢