spring - Feign ErrorDecoder 未被调用 - 如何配置 feign 以使用它?

标签 spring error-handling spring-cloud-feign feign openfeign

据我了解,当请求响应状态码!= 2xx 时,将调用 feign ErrorDecoder 的 decode() 方法。通过调试我的测试,我发现我的 CustomErrorDecoder 的 decode() 方法没有被调用,例如504 或 404。我尝试了两种配置方式:
将其作为 Bean 包含在客户端配置中:

    @Bean
    public CustomErrorDecoder customErrorDecoder() {
        return new CustomErrorDecoder();
    }
或将其写入应用程序配置:
feign:
  client:
    config:
      myCustomRestClientName:
        retryer: com.a.b.some.package.CustomRetryer
        errorDecoder: com.a.b.some.package.CustomErrorDecoder
两种方式都不会调用 ErrorDecoder。我究竟做错了什么? Bean 正在实例化,我的 CustomErrorDecoder 如下所示:
@Component
public class CustomErrorDecoder implements ErrorDecoder {

    private final ErrorDecoder defaultErrorDecoder = new Default();

    @Override
    public Exception decode(String s, Response response) {
        Exception exception = defaultErrorDecoder.decode(s, response);

        if (exception instanceof RetryableException) {
            return exception;
        }

        if (response.status() == 504) {
            // throwing new RetryableException to retry 504s
        }
        return exception;
    }
}

更新:
我在这个 git repo 中创建了一个最小的可重现示例。请查看提交历史以找到我尝试过的 3 种方法。

最佳答案

问题是你的假客户端使用 feign.Response作为返回类型:

import feign.Param;
import feign.RequestLine;
import feign.Response;

public interface TestEngineRestClient {

    @RequestLine(value = "GET /{uuid}")
    Response getReport(@Param("uuid") String uuid);
}
在这种情况下,Feign 将其处理委托(delegate)给开发人员 - 例如,您可以检索 HTTP 状态和响应正文并使用它做一些事情。
有兴趣的可以看看feign.SynchronousMethodHandler的源码, executeAndDecode部分。
要解决此问题,请替换 Response.class在状态码 = 2xx(可能是某些 DTO 类)的正确响应的情况下,使用所需的类型。我做了一个PR我已将其更改为 String为简单起见。

关于spring - Feign ErrorDecoder 未被调用 - 如何配置 feign 以使用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62453241/

相关文章:

java - 有没有办法将 java bean 验证 api 与 Spring RestTemplate 集成

rust - 匹配和解包之间的不同行为

spring-cloud - Hystrix 和 Ribbon 超时警告

java - Spring-cloud-starter-openfeign : SSL handshake exception with feign-httpclient

spring-cloud-feign - Feign ErrorDecoder : retrieve the original message

java - 如何配置 Jetspeed 用户密码验证

java - 为什么在authenticate(..)上返回的Authentication对象仍然需要包含凭据?

java - Spring MVC + 安全性。字符编码过滤器不起作用

PHP:记录生产中 fatal error 的堆栈跟踪

mysql - SQL 插入 Access 2010 时出错