Centralized error handling for FeignClient: ErrorDecoder, Resilience4j, and custom exceptions with PathVariable context

1 week ago 11
ARTICLE AD BOX

I am developing a Spring Boot application that consumes external APIs via spring-cloud-starter-openfeign. I am also using Resilience4j for Circuit Breaker and Retries.

My goal is to implement a centralized error handling strategy that covers:

Business Exceptions: Mapping 4xx/5xx status codes to custom exceptions.

Contextual Data: I want my custom exceptions to carry the original PathVariable (or request parameters) to help with logging and debugging in the @ControllerAdvice.

Resilience Failures: Handling timeouts and 503 errors (often wrapped in Feign's RetryableException) without losing the ability to trigger the Circuit Breaker.

The Problem:
Feign wraps most network issues in a RetryableException. Furthermore, I'm struggling to find the best way to extract a specific PathVariable from the request when an error occurs so I can instantiate my custom exception with that context (e.g., UserNotFoundException(userId)).

@FeignClient(name = "user-service", configuration = FeignConfig.class) public interface UserClient { @GetMapping("/users/{id}") UserResponse getUserById(@PathVariable("id") String id); }

Questions:

How can I implement an ErrorDecoder that extracts the {id} from the request path to include it in a custom exception?

What is the best practice to handle these exceptions centrally? Should I let the ErrorDecoder throw the exception and catch it in a @RestControllerAdvice?

How does the Resilience4j Circuit Breaker interact with custom exceptions thrown by the ErrorDecoder? Do I need to explicitly tell Resilience4j which exceptions should (or shouldn't) trigger a state change?

I would appreciate a concise example showing the integration of ErrorDecoder (with request context) + Resilience4j + @ControllerAdvice.


Read Entire Article