Spring Cloud OpenFeign 自定义 ErrorDecoder
OpenFeign Spring Boot 大约 1813 字示例代码
配置类
形参中注入Decoder
(默认启动时就会注入Decoder
,参见默认配置FeignClientsConfiguration
),解析response
。
使用jackson
的JsonNode
接收,由框架自己识别类型,不用判断数组或对象。
import com.fasterxml.jackson.databind.JsonNode;
import feign.codec.Decoder;
import feign.codec.ErrorDecoder;
import java.io.IOException;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.ResponseEntity;
import org.springframework.http.ResponseEntity.BodyBuilder;
@Configuration
public class FeignSpecificDecoderConfig {
private final ObjectFactory<HttpMessageConverters> messageConverters;
public FeignSpecificDecoderConfig(ObjectFactory<HttpMessageConverters> objectFactory) {
this.messageConverters = objectFactory;
}
@Bean
public ErrorDecoder specificErrorDecoder(Decoder decoder) {
return (methodKey, response) -> {
TestException testException = new TestException();
BodyBuilder builder = ResponseEntity.status(response.status());
try {
Object decode = decoder.decode(response, JsonNode.class);
ResponseEntity<Object> body = builder
.body(decode);
testException.setResponse(body);
} catch (Exception e) {
testException.setResponse(builder.build());
}
return testException;
};
}
}
异常包装类
public class TestException extends RuntimeException {
private Object response;
public Object getResponse() {
return response;
}
public void setResponse(Object response) {
this.response = response;
}
}
阅读 427 · 发布于 2022-10-25
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb扫描下方二维码关注公众号和小程序↓↓↓

昵称:
随便看看
换一批
-
Spring Boot2 关闭 Spring Security 权限验证阅读 13191
-
Android 查看签名文件 jsk 的 SHA1,apk 签名验证阅读 4619
-
minikube start Unable to determine current user's administrator privileges阅读 335
-
Kubernetes kubectl top 命令报 error: Metrics API not available阅读 1254
-
IDEA Cannot resolve plugin org.apache.maven.plugins:maven-clean-plugin:2.5阅读 1956
-
Linux 之 CentOS yum 安装 Nginx阅读 2483
-
MySQL 内置函数之字符串函数阅读 2002
-
GoLand defer 提示 Unhandled error 解决方法阅读 6991
-
JMeter 当前接口请求失败停止请求下一个接口阅读 2149
-
Java 中判断奇偶性的方法阅读 1681