SoFunction
Updated on 2025-04-20

SpringBoot catches feign throws exception

Preface

When using Springboot, when using feign client as the http request tool, when the interface throws exception information, the exception cannot be caught using global exceptions.

feign exception global capture

Define an exception class

@Getter
public class BusinessException extends RuntimeException {

    private String message;

    private int code;

    public BusinessException(String message, int code) {
         = message;
         = code;
    }

    public BusinessException(String message) {
        super(message);
         = message;
    }



}

Catch feign request exception

@Slf4j
@Configuration
public class FeignExceptionConfig {

    @Bean
    public ErrorDecoder feignError() {
        return (key, response) -> {
            if (() != ()) {
                try {
                    String data = (().asInputStream());
                    ("feignRequest error,The return value is:{{}}", data);
                    throw new BusinessException(data);
                } catch (BusinessException e) {
                    throw e;
                } catch (Exception e) {
                    ("Exception information is:", e);
                    throw new RuntimeException(e);
                }
            }

            // Leave other exceptions to Default for decoding and processing            // Just use a singleton here, Default doesn't need to go to new every time            return new ().decode(key, response);
        };
    }

}

Or add this to global exception capture

@ExceptionHandler()
@ResponseStatus(HttpStatus.BAD_REQUEST)
public String handleFeignException(FeignException ex) {
    ("feign exception handling information", ex);
    return ex.contentUTF8();
}

Summarize

Feign client is a powerful request tool, but exception handling sometimes requires additional processing

This is the end of this article about SpringBoot catching feign exceptions. For more related content on SpringBoot catching feign exceptions, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!