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

相关推荐
ping某6 分钟前
一个“日志备份”需求,为什么会牵出整个 Linux 日志系统?
后端·架构
血小溅24 分钟前
Spring AI 对 Skill/MCP 的支持全景整理
后端
晓杰'35 分钟前
从0到1实现Balatro游戏后端(8):Skip Blind与Tag奖励机制设计与实现
后端·websocket·typescript·项目实战·nestjs·状态管理·游戏服务器
叫我:松哥38 分钟前
基于Flask框架的校园二手书籍交易平台,注重校园场景的特殊需求,通过学号认证保障用户真实性
后端·python·sqlite·flask·bootstrap
终将老去的穷苦程序员1 小时前
基于SpringBoot的餐饮管理系统
java·spring boot·后端
心之伊始1 小时前
Spring AI Tool Calling 实战:让 Java Agent 调用本地 Bean 工具方法
java·spring boot·agent·spring ai·tool calling
张忠琳1 小时前
【Go 1.26.4】Golang Map 深度解析
开发语言·后端·golang
一条泥憨鱼2 小时前
Java开发效率神器:Lombok从入门到精通!
java·后端·学习·开发·lombok
熠熠仔2 小时前
Spring Boot 与 MyBatis-Plus 空间几何数据集成指南
spring boot·后端·mybatis
AI 小老六2 小时前
Google AX 控制面拆解:分布式 Agent 如何把断点恢复、审计策略和执行调度收进同一条链路
人工智能·分布式·后端·ai·架构·ai编程