spring feign client exception handling
Not the same issue, but this helped in my situation. OpenFeign's FeignException doesn't bind to a specific HTTP status (i.e. doesn't use Spring's @ResponseStatus annotation), which makes Spring default to 500 whenever faced with a FeignException. That's okay because a FeignException can have numerous causes that can't be related to a particular HTTP status.
However you can change the way that Spring handles FeignExceptions. Simply define an ExceptionHandler that handles the FeignException
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(FeignException.class)
public String handleFeignStatusException(FeignException e, HttpServletResponse response) {
response.setStatus(e.status());
return "feignError";
}
}
This example makes Spring return the same HTTP status that you received
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
.