Feign 返回的异常处理解析

参考:https://www.jianshu.com/p/d829fd5981b4

参考:https://my.oschina.net/xiaominmin/blog/2986631

 

ErrorDecoder类


import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sany.gcp.infra.feign.common.FeighErrorDecodeException;
import com.sany.gcp.infra.feign.common.FeighErrorResult;
import feign.*;
import feign.codec.ErrorDecoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;

import java.io.IOException;

/**
 * feigh配置请求拦截器
 * @author gw_liuzp 2021/6/9 17:53
 */
@Slf4j
//@Configuration
public class OAuthFeignConfiguration implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate template) {
        //template.header("Authorization", "Basic ZGhnYXRlOnBwMTIz");
    /*    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        Enumeration<String> headerNames = request.getHeaderNames();
        if (headerNames != null) {
            while (headerNames.hasMoreElements()) {
                String name = headerNames.nextElement();
                String values = request.getHeader(name);
                template.header(name, values);
            }
        }*/
    }

    @Bean
    public ErrorDecoder errorDecoder() {
        return new UserErrorDecoder();
    }
    /**
     * 自定义错误
     */
    public class UserErrorDecoder implements ErrorDecoder {
        @Override
        public Exception decode(String methodKey, Response response) {
            Exception exception = null;
            try {
                // 获取原始的返回内容
//                String json = Util.toString(response.body().asReader(Charset.defaultCharset()));
                String json = Util.toString(response.body().asReader());
                // 将返回内容反序列化为Result,这里应根据自身项目作修改
                ObjectMapper objectMapper = new ObjectMapper();
                // 忽略未知json字段
                objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
                FeighErrorResult result = objectMapper.readValue(json,FeighErrorResult.class);
                // 业务异常抛出简单的 RuntimeException,保留原来错误信息
                if (!result.getSuccess()) {
                    exception = new FeighErrorDecodeException(result.getCode(),result.getMessage());
                }
            } catch (IOException ex) {
                log.error(ex.getMessage(), ex);
            }
            return exception;
}
}
       

 

自定义异常类

import lombok.Data;

/**
 * feigh调用错误解析器异常类
 * @author gw_liuzp 2021/6/10 12:23
 */
@Data
public class FeighErrorDecodeException extends RuntimeException{
    private String code;
    private String message;

    public FeighErrorDecodeException(String code, String message){
        super(message);
        this.code = code;
        this.message = message;
    }
}

 

定义接受json结构对象

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

/**
 * feigh调用错误信息对象
 * @author gw_liuzp 2021/6/10 9:18
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class FeighErrorResult implements Serializable {
//    {
//        "error":"unauthorized",
//            "error_description":"hoth.warn.accountLocked",
//            "success":false,
//            "code":"hoth.warn.accountLocked",
//            "message":"您的账户已锁定,请通过找回密码解锁,或联系平台运维中心"
//    }
    private String error;
    private String error_description;
    private Boolean success;
    private String code;
    private String message;

}

 

在feign注解配置configuration

@FeignClient(value = "hzero-oauth", path = "/oauth", configuration = OAuthFeignConfiguration.class, fallbackFactory = OAuthServiceFallBack.class)

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在使用 Feign 进行远程服务调用时,可能会遇到各种异常情况,比如连接超时、请求失败等。Feign 提供了一些异常处理机制,可以方便地对这些异常进行统一处理。 Feign异常处理主要包括两个方面: 1. 对于 HTTP 响应码在 200 ~ 299 范围内的请求,Feign 不会抛出异常,而是将响应数据封装为方法返回值。如果响应码不在该范围内,Feign 会抛出 FeignException 异常。 2. FeignException 是 Feign 中的基础异常类,它包含了请求的相关信息,如请求方法、请求 URL、请求头、响应状态码等。我们可以通过捕获 FeignException 异常来统一处理 Feign 调用出现的异常情况。 例如,我们可以使用 @FeignClient 中的 fallback 属性来指定一个实现了当前接口的熔断器类,在请求失败时会触发该熔断器中的方法,从而实现对异常的处理。具体实现可以参考以下代码: ```java @FeignClient(name = "service-provider", fallback = MyFallback.class) public interface MyFeignClient { @RequestMapping("/hello") String hello(); } @Component public class MyFallback implements MyFeignClient { @Override public String hello() { return "fallback"; } } ``` 在上述代码中,我们定义了一个名为 MyFeignClient 的 Feign 接口,并指定了 fallback 属性为 MyFallback.class。当调用 hello 方法时,如果请求失败,就会触发 MyFallback 类中的 hello 方法,并返回 "fallback" 字符串。 当然,除了使用 fallback 属性之外,我们还可以通过实现 ErrorDecoder 接口来自定义 FeignException 的处理方式,例如将异常信息记录到日志中,或者将异常信息转换为业务自定义的异常类型等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值