I have a feign client like this
@FeignClient(name = "client")
public interface SomeClient {
@RequestLine("GET /?q={q}")
void execute(URI baseUrl, @Param("q") String q) throws SomeExceptionInMyCode;
}
Looking to this throws SomeExceptionInMyCode
I'm asking myself when this exception will be thrown. There is no configuration for client defined, no error decoder. Exception looks like this.
public class SomeExceptionInMyCode extends Exception{
private final int statusCode;
private final String reason;
private final String body;
// getters and setters
}
Will there be an automatic attempt to decode HTTP response to this exception in case of failure? Or throws SomeExceptionInMyCode
is useless and can be removed without any impact.
I searched inside my code and this exception is never created.
Will there be an automatic attempt to decode http response to this exception in case of failure?
Nope, it doesn't work like this and the SomeExceptionMyCode
will not be thrown. The throws
clause is useless. Even if the endpoint throws this exception from its implementation, it will be wrapped as a cause of FeignException
.
The correct way to handle feign client exceptions is using Custom exception handling implementing ErrorDecoder
:
public class StashErrorDecoder implements ErrorDecoder {
@Override
public Exception decode(String methodKey, Response response) {
if (response.status() >= 400 && response.status() <= 499) {
// return 4XX exception
}
if (response.status() >= 500 && response.status() <= 599) {
// return 5XX exception
}
}
}
At this point you can perform the custom exception creation and rethrowing.
An alternative solution is to use Spring-alike @RestControllerAdvice
:
@RestControllerAdvice
public class ExceptionHandler {
@ExceptionHandler(FeignException.class)
public String handleFeignStatusException(FeignException e, HttpServletResponse response) {
// ...
}
}