赞
踩
项目采用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(); } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。