Springboot捕获feign抛出的异常

前言

使用Springboot时,使用feign客户端作为http请求工具时,当接口抛出异常信息时,使用全局异常是捕获不了异常的

feign异常全局捕获

定义一个异常类

scala 复制代码
@Getter
public class BusinessException extends RuntimeException {

    private String message;

    private int code;

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

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



}

捕获feign请求异常

vbnet 复制代码
@Slf4j
@Configuration
public class FeignExceptionConfig {

    @Bean
    public ErrorDecoder feignError() {
        return (key, response) -> {
            if (response.status() != HttpStatus.OK.value()) {
                try {
                    String data = IOUtils.toString(response.body().asInputStream());
                    log.error("feign请求错误,返回值为:{{}}", data);
                    throw new BusinessException(data);
                } catch (BusinessException e) {
                    throw e;
                } catch (Exception e) {
                    log.error("异常信息为:", e);
                    throw new RuntimeException(e);
                }
            }

            // 其他异常交给Default去解码处理
            // 这里使用单例即可,Default不用每次都去new
            return new ErrorDecoder.Default().decode(key, response);
        };
    }

}

或者在全局异常捕获加上这个

less 复制代码
@ExceptionHandler(FeignException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public String handleFeignException(FeignException ex) {
    log.error("feign异常处理信息", ex);
    return ex.contentUTF8();
}

总结

feign客户端是一个强大的请求工具,但是异常处理有时候得额外处理

相关推荐
学长毕设1 小时前
基于SpringBoot的儿童慈善捐赠管理系统-附源码
java·spring boot·后端
皮皮林5512 小时前
GitHub Copilot:你可以暂时不用,但别不知道它有多强
后端
学长毕设2 小时前
基于SpringBoot非遗文化展示与传播平台设计与实现-附源码
java·spring boot·后端
杨凯凡3 小时前
Spring Boot SSE 上线后不实时、频繁断线?Nginx 缓冲、心跳与连接回收实战
spring boot·后端·nginx
锋行天下3 小时前
langgraph 全栈项目(三)
前端·人工智能·后端
金銀銅鐵3 小时前
用 Swing 重做操作数栈演示
java·jvm·后端
锋行天下4 小时前
langgraph 全栈项目(二)
前端·人工智能·后端
锋行天下5 小时前
langgraph全栈项目(一)
前端·人工智能·后端
学长毕设5 小时前
基于SpringBoot的游戏攻略社区交流系统-附源码
spring boot·后端·游戏
程序员cxuan5 小时前
不得了,Google 造反了,Opus 5.5 又被干了
人工智能·后端·程序员