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 dont 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.
Feign Client It's not only about ease code writing ? Providing Feign Client in Spring Boot toolbox not only for ease code writing purpose for developer instead of using RestTemplate, but also it has an architectural decision and design.
Let's implement the Feign in our project and invoke other microservices using Feign. Step 1: Select currency-conversion-service project. Step 2: Open the pom. xml and add the Feign dependency.
Spring WebClient is a non-blocking reactive client to make HTTP requests. Feign is a library which helps us to create declarative REST clients easily with annotations and it provides better abstraction when we need to call an external service in Microservices Architecture.
I'm late to party but here are my 2 cents. We had same use case to handle exceptions based on error code and we used custom ErrorDecoder
.
public class CustomErrorDecoder implements ErrorDecoder {
@Override
public Exception decode(String methodKey, Response response) {
String requestUrl = response.request().url();
Response.Body responseBody = response.body();
HttpStatus responseStatus = HttpStatus.valueOf(response.status());
if (responseStatus.is5xxServerError()) {
return new RestApiServerException(requestUrl, responseBody);
} else if (responseStatus.is4xxClientError()) {
return new RestApiClientException(requestUrl, responseBody);
} else {
return new Exception("Generic exception");
}
}
}
Return @Bean
of above class in FeignClientConfiguration
class.
public class MyFeignClientConfiguration {
@Bean
public ErrorDecoder errorDecoder() {
return new CustomErrorDecoder();
}
}
Use this as your config class for FeignClient.
@FeignClient(value = "myFeignClient", configuration = MyFeignClientConfiguration.class)
Then you can handle these exceptions using GlobalExceptionHandler
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With