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

相关推荐
Coder_Boy_2 分钟前
Spring Boot 事务回滚异常 UnexpectedRollbackException 详解(常见问题集合)
java·spring boot·后端
风象南4 分钟前
SpringBoot 实现网络限速
后端
源代码•宸9 分钟前
Golang语法进阶(定时器)
开发语言·经验分享·后端·算法·golang·timer·ticker
期待のcode11 分钟前
TransactionManager
java·开发语言·spring boot
计算机学姐13 分钟前
基于SpringBoot的汽车租赁系统【个性化推荐算法+数据可视化统计】
java·vue.js·spring boot·后端·spring·汽车·推荐算法
8***f39513 分钟前
Spring 中使用Mybatis,超详细
spring·tomcat·mybatis
我是人✓15 分钟前
Spring IOC入门
java·数据库·spring
好好研究16 分钟前
SpringBoot小案例打包执行流程
java·spring boot·后端
BingoGo17 分钟前
免费可商用商业级管理后台 CatchAdmin V5 正式发布 插件化与开发效率的全面提升
vue.js·后端·php
IT_陈寒28 分钟前
SpringBoot 3.0实战:这5个新特性让你的开发效率提升50%
前端·人工智能·后端