Video in progress
How do you configure timeouts and error responses in a Spring Cloud OpenFeign client?
I set the timeouts per client under spring.cloud.openfeign.client.config.<name>, and I turn 4xx/5xx responses into domain exceptions through my own ErrorDecoder.
📖 Answer
A Feign interface is convenient, but you shouldn't trust the default settings. Give each external service its own timeout:
spring:
cloud:
openfeign:
client:
config:
default:
connect-timeout: 1000
read-timeout: 3000
payment-service:
read-timeout: 5000 # payment responds more slowly
@FeignClient(name = "payment-service", url = "${payment.base-url}")
public interface PaymentClient {
@PostMapping("/payments")
PaymentResponse create(@RequestBody PaymentRequest request,
@RequestHeader("Idempotency-Key") String key);
}
By default, error responses come back as a FeignException. So I don't have to check status codes in business code, I write an ErrorDecoder:
public class PaymentErrorDecoder implements ErrorDecoder {
public Exception decode(String method, Response r) {
return switch (r.status()) {
case 404 -> new PaymentNotFoundException();
case 409 -> new PaymentConflictException();
default -> new ErrorDecoder.Default().decode(method, r);
};
}
}
A note: the Spring team recommends @HttpExchange interfaces (on top of RestClient or WebClient) for new projects, while OpenFeign is mostly in maintenance mode. If an existing project has Feign, you can keep using it.
Sign up to mark studied questions and save your progress.