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

相关推荐
金色天际线-2 小时前
Nginx 优化与防盗链配置指南
java·后端·spring
皮皮林5518 小时前
SpringBoot 全局/局部双模式 Gzip 压缩实战:14MB GeoJSON 秒变 3MB
java·spring boot
weixin_456904279 小时前
Spring Boot 用户管理系统
java·spring boot·后端
奔跑吧邓邓子9 小时前
【Java实战㉞】从0到1:Spring Boot Web开发与接口设计实战
java·spring boot·实战·web开发·接口设计
茶本无香9 小时前
深入理解Spring Boot的EnvironmentPostProcessor:环境处理的黑科技
spring boot
奔跑吧邓邓子9 小时前
【Java实战㉝】Spring Boot实战:从入门到自动配置的进阶之路
java·spring boot·实战·自动配置
ONLYOFFICE9 小时前
【技术教程】如何将ONLYOFFICE文档集成到使用Spring Boot框架编写的Java Web应用程序中
java·spring boot·编辑器
cyforkk10 小时前
Spring 异常处理器:从混乱到有序,优雅处理所有异常
java·后端·spring·mvc
Z_z在努力10 小时前
【杂类】Spring 自动装配原理
java·spring·mybatis
程序员爱钓鱼10 小时前
Go语言实战案例-开发一个Markdown转HTML工具
前端·后端·go