我有一些假装客户端发送请求其他微服务。
@FeignClient(name="userservice")
public interface UserClient {
@RequestMapping(
method= RequestMethod.GET,
path = "/userlist")
String getUserByid(@RequestParam(value ="id") String id);
}
现在我发送这样的请求
try {
String responseData = userClient.getUserByid(id);
return responseData;
}
catch(FeignException e)
{
logger.error("Failed to get user", id);
}
catch (Exception e)
{
logger.error("Failed to get user", id);
}
这里的问题是如果发生任何FeignException我没有得到任何错误代码。
我需要在其他APIS中发送相应的错误代码以发送给调用者
那么如何提取错误代码呢?我想提取错误代码并构建responseEntity
我得到了qazxsw poi代码,但不知道我的功能究竟如何使用。
你试图在假装客户端上实现FallbackFactory吗?
在create方法上,在返回之前,您可以使用以下代码段检索http状态代码:
https://cloud.spring.io/spring-cloud-netflix/multi/multi_spring-cloud-feign.html#spring-cloud-feign-hystrix-fallback
例如:
String httpStatus = cause instanceof FeignException ? Integer.toString(((FeignException) cause).status()) : "";
}
不一样的问题,但这在我的情况下有所帮助。 OpenFeign的FeignException没有绑定到特定的HTTP状态(即不使用Spring的@ResponseStatus注释),这使得Spring在遇到FeignException时默认为500。这没关系,因为FeignException可能有许多原因与特定的HTTP状态无关。
但是,您可以更改Spring处理FeignExceptions的方式。只需定义一个处理FeignException的ExceptionHandler
@FeignClient(name="userservice", fallbackFactory = UserClientFallbackFactory.class)
public interface UserClient {
@RequestMapping(
method= RequestMethod.GET,
path = "/userlist")
String getUserByid(@RequestParam(value ="id") String id);
}
@Component
static class UserClientFallbackFactory implements FallbackFactory<UserClient> {
@Override
public UserClient create(Throwable cause) {
String httpStatus = cause instanceof FeignException ? Integer.toString(((FeignException) cause).status()) : "";
return new UserClient() {
@Override
public String getUserByid() {
logger.error(httpStatus);
// what you want to answer back (logger, exception catch by a ControllerAdvice, etc)
}
};
}
此示例使Spring返回与您收到的相同的HTTP状态