Java OpenResty Spring Spring Boot MySQL Redis MongoDB PostgreSQL Linux Android Nginx 面试 小程序 Arthas JVM AQS juc Kubernetes Docker DevOps


Spring Cloud OpenFeign 自定义 ErrorDecoder

OpenFeign Spring Boot 大约 1813 字

示例代码

配置类

形参中注入Decoder(默认启动时就会注入Decoder,参见默认配置FeignClientsConfiguration),解析response

使用jacksonJsonNode接收,由框架自己识别类型,不用判断数组或对象。

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;
    }
}
阅读 102 · 发布于 2022-10-25

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb

扫描下方二维码关注公众号和小程序↓↓↓

扫描二维码关注我
昵称:
随便看看 换一批