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

相关推荐
[email protected]1 小时前
ASP.NET Core 中实现 Markdown 渲染中间件
后端·中间件·asp.net·.netcore
hello_ejb34 小时前
聊聊Spring AI Alibaba的SentenceSplitter
人工智能·python·spring
eternal__day6 小时前
Spring Boot 实现验证码生成与校验:从零开始构建安全登录系统
java·spring boot·后端·安全·java-ee·学习方法
海天胜景7 小时前
HTTP Error 500.31 - Failed to load ASP.NET Core runtime
后端·asp.net
海天胜景7 小时前
Asp.Net Core IIS发布后PUT、DELETE请求错误405
数据库·后端·asp.net
宛如昨晚没早睡9 小时前
SpringBoot的自动配置和起步依赖原理
spring boot
源码云商9 小时前
Spring Boot + Vue 实现在线视频教育平台
vue.js·spring boot·后端
RunsenLIu11 小时前
基于Django实现的篮球论坛管理系统
后端·python·django
Micro麦可乐12 小时前
最新Spring Security实战教程(十四)OAuth2.0精讲 - 四种授权模式与资源服务器搭建
java·服务器·spring boot·spring·spring security·oauth2·oauth2授权
HelloZheQ12 小时前
Go:简洁高效,构建现代应用的利器
开发语言·后端·golang