美文网首页Spring Cloud 相关文章
SpringCloud-feign客户端统一处理下游服务自定义异

SpringCloud-feign客户端统一处理下游服务自定义异

作者: KingdomCoder | 来源:发表于2018-09-29 15:24 被阅读0次

经过尝试和查阅资料,Springcloud处理下游服务的异常是是通过默认的ErrorDecoder实现处理的,最终上游业务获取抛出的异常处理都是FeignException处理,到时上游业务统一异常处理造成困扰,下面解决方式为:

@Slf4j
@Configuration
public class ExceptionErrorDecoder implements ErrorDecoder {

   @Override
   public Exception decode(String methodKey, Response response) {
       try {
           if (response.body() != null) {
               ExceptionInfo exceptionInfo = JSON.parseObject(Util.toString(response.body().asReader()), new TypeReference<ExceptionInfo>() {
               });
               Class clazz = Class.forName(exceptionInfo.getException());
               return (Exception) clazz.getDeclaredConstructor(String.class).newInstance(exceptionInfo.getMessage());
           }

       } catch (Exception e) {
           e.printStackTrace();
       }
       return FeignException.errorStatus(methodKey, response);
   }
}

主要分析了返回的body的内容,主要结构如下:

{
    "timestamp": 1538202442624,
    "status": 500,
    "error": "Internal Server Error",
    "exception": "com.crazy.cloud.common.exception.DataConflictException",
    "message": "手机已注册",
    "path": "/users"
}
@Data
public class ExceptionInfo{

   private Long timestamp;

   private Integer status;
//异常包结构-"com.crazy.cloud.common.exception.DataConflictException"
   private String exception;
 //信息--手机已注册
   private String message;

   private String path;

   private String error;


}

分析能够得到--我们有了完整的包结构和message,所以我们完全可以通过反射生成一个同样的异常对象,这样我们在上游业务就可以被controllerAdvice捕获到,从而达到统一异常处理的目的。

微信公众号欢迎关注.jpg

相关文章

网友评论

    本文标题:SpringCloud-feign客户端统一处理下游服务自定义异

    本文链接:https://www.haomeiwen.com/subject/kzxboftx.html