By default, Spring Cloud Netflix Feign throws FeignException for any type errors in any situation, but it is not always suitable and you don't want this same exception for every situation in your project. Netflix Feign allows you to set your own application-specific exception instead. You can do it easily by providing your own implementation of feign.codec.ErrorDecoder to Feign.builder.errorDecoder().
Let's see an example of such an ErrorDecoder implementation:
public class AccountErrorDecoder implements ErrorDecoder { @Override public Exception decode(String methodKey, Response response) { if (response.status() >= 400 && response.status() <= 499) { return new AccountClientException( response.status(), response.reason() ); } if (response.status() >= 500 && response.status() <= 599) { return new AccountServerException( response.status(), response.reason() ); } return errorStatus(methodKey, response); } }
Now you can use the preceding created exception by providing your Feign.builder(). Let's see the following example:
return Feign.builder() .errorDecoder(new AccountErrorDecoder()) .target(AccountService.class, url);
AccountErrorDecoder sets a custom error decoder to the Feign Builder API. This code is simply adding a custom error decoder to the Feign client. We can create custom decoders and encoders for the Feign Builder API.