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客户端是一个强大的请求工具,但是异常处理有时候得额外处理

相关推荐
一只爱撸猫的程序猿14 分钟前
构建一个简单的智能文档问答系统实例
数据库·spring boot·aigc
ruokkk19 分钟前
重启Eureka集群中的节点,对已经注册的服务有什么影响
后端
一线大码25 分钟前
项目中怎么确定线程池的大小
java·后端
LNin30 分钟前
Spring AI 自定义数据库持久化的ChatMemory
后端
crud31 分钟前
Spring Boot 3 整合 Swagger:打造现代化 API 文档系统(附完整代码 + 高级配置 + 最佳实践)
java·spring boot·swagger
天天摸鱼的java工程师36 分钟前
从被测试小姐姐追着怼到运维小哥点赞:我在项目管理系统的 MySQL 优化实战
java·后端·mysql
专注VB编程开发20年1 小时前
asp.net mvc如何简化控制器逻辑
后端·asp.net·mvc
用户6757049885021 小时前
告别数据库瓶颈!用这个技巧让你的程序跑得飞快!
后端
鳄鱼杆1 小时前
服务器 | Centos 9 系统中,如何部署SpringBoot后端项目?
服务器·spring boot·centos