据我了解,当请求响应状态码!= 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/