I have some fiegn client to send request other micro service.
@FeignClient(name="userservice")
public interface UserClient {
@RequestMapping(
method= RequestMethod.GET,
path = "/userlist"
)
String getUserByid(@RequestParam(value ="id") String id);
}
Now I am sending request like this
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);
}
Here the problem is if any FeignException
happens I don't get any error code.
I need to send a corresponding error codes in other APIS to send to caller
So how to extract the error code? I want to extract error code and build a responseEntity
I got this code but dont know how exactly I can use in my function.
did you try to implement FallbackFactory on your feign client ?
On the create method, before return, you can retrieve the http status code with this snippet :
String httpStatus = cause instanceof FeignException ? Integer.toString(((FeignException) cause).status()) : "";
Exemple :
@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)
}
};
}
}