当前位置:   article > 正文

Feign 获取异常_usererrordecoder

usererrordecoder

     项目采用springCloud,那么Feign就避免不了,更惨的是自己负责后台中台,老板需要后台的接口全部都来源于后台中台,于是后台中台就需要转接其他所有微服务的接口。而接口报错,客户端就需要捕捉到异常,并抛给前端。如果在开启熔断之后,这个异常会被消化,要拿到服务端异常,feign.hystrix.enable需要设置为false

编写feign异常拦截器,获取到feign所有异常,并抛出

public class UserErrorDecoder implements ErrorDecoder {

    private Logger log = LoggerFactory.getLogger(getClass());
    ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public Exception decode(String methodKey, Response response) {
        int status = response.status();
        log.info("status:" + status);
        ExceptionInfo ei = null;
        try {
            String body = Util.toString(response.body().asReader());
            ei = this.objectMapper.readValue(body.getBytes(StandardCharsets.UTF_8), ExceptionInfo.class);

            log.info("调用接口状态:{},{}", ei.getStatus(), ei.getDetail());
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (status != 200) {
            assert ei != null;
            throw  new ApiException("调用接口状态:" + ei.getStatus() + "," + ei.getDetail() + "");
        }
        return defaultErrorDecoder(methodKey, response);
    }

    private Exception defaultErrorDecoder(String methodKey, Response response) {
        return new ErrorDecoder.Default().decode(methodKey, response);
    }

    @Bean
    public ErrorDecoder errorDecoder() {
        return new UserErrorDecoder();
    }
}
public class ExceptionInfo {
    private String type;
    private String title;
    private Integer status;
    private String detail;
    private String path;
    private String message;
}

为 Feign 配置 ErrorDecoder

@Configuration
@EnableFeignClients(basePackages = "xyz.ttooc.bcia.backend")
@Import(FeignClientsConfiguration.class)
public class FeignConfiguration {

    @Bean
    public ErrorDecoder errorDecoder() {
        return new UserErrorDecoder();
    }
}

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/84625
推荐阅读
相关标签
  

闽ICP备14008679号