@FeignClient定义fallbackFactory捕捉feign异常

 1.在@FeignClient添加fallbackFactory属性

@FeignClient(name = "server-user",path = "/wyc/user",contextId = "UserInviteActFeignClient",fallbackFactory = UserInviteActFallback.class
        //,url = "http://localhost:9910"
)
public interface UserInviteActFeignClient {

    @PostMapping(value = "/checkWorkerIdentity")
    BaseResp checkWorkerIdentity(@RequestBody CheckWorkerIdentityReq request);

}

2.定义类:UserInviteActFallback.java

@Component
public class UserInviteActFallback implements FallbackFactory<UserInviteActFeignClient> {

    @Override
    public UserInviteActFeignClient create(Throwable throwable) {
        return new UserInviteActFeignClient() {
            @Override
            public BaseResp checkWorkerIdentity(CheckWorkerIdentityReq request) {
                BaseResp resp = new BaseResp();
                //异常处理
                FeginExceptionUtil.exception(throwable,resp);
                return resp;
            }
        };
    }
}

3.定义FeginExceptionUtil.exception方法处理异常

@Slf4j
public class FeginExceptionUtil {

    public static void exception(Throwable e, BaseResponse resp){
        if(e instanceof FeignException){
            FeignException f = (FeignException)e;
            String url = f.request().url();
            int status = f.status();
            String message = f.getMessage();
            log.error("feign调用异常:"+message);
            if(status == 404){
                resp.setMsg("端点未找到:"+url);
                return;
            }
            if(message.contains("Read timed out")){
                resp.setMsg("服务处理请求超时:"+url);
                return;
            }
            if(message.contains("connect timed out")){
                resp.setMsg("服务连接超时:"+url);
                return;
            }
        }else if(e instanceof RuntimeException){
            RuntimeException f = (RuntimeException)e;
            String message = f.getMessage();
            if(StrUtil.isNotEmpty(message)){
                //com.netflix.client.ClientException: Load balancer does not have available server for client: workordercenter-service
                if(message.contains("Load balancer does not have available server for client")){
                    String[] split = message.split(":");
                    if(split.length > 2){
                        resp.setMsg("没有找到可用的服务:"+split[2]);
                    }
                }else{
                    log.error("feign调用异常:"+message);
                }
            }
        }
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值