Spring Cloud OpenFeign 自定义 ErrorDecoder
OpenFeign Spring Boot About 1,813 words示例代码
配置类
形参中注入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;
}
}
Views: 1,776 · Posted: 2022-10-25
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb/LiteNote扫描下方二维码关注公众号和小程序↓↓↓
Loading...