当前位置: 代码网 > it编程>编程语言>Java > SpringBoot捕获feign抛出异常的方法

SpringBoot捕获feign抛出异常的方法

2025年04月20日 Java 我要评论
前言使用springboot时,使用feign客户端作为http请求工具时,当接口抛出异常信息时,使用全局异常是捕获不了异常的feign异常全局捕获定义一个异常类@getterpublic class

前言

使用springboot时,使用feign客户端作为http请求工具时,当接口抛出异常信息时,使用全局异常是捕获不了异常的

feign异常全局捕获

定义一个异常类

@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请求异常

@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);
        };
    }

}

或者在全局异常捕获加上这个

@exceptionhandler(feignexception.class)
@responsestatus(httpstatus.bad_request)
public string handlefeignexception(feignexception ex) {
    log.error("feign异常处理信息", ex);
    return ex.contentutf8();
}

总结

feign客户端是一个强大的请求工具,但是异常处理有时候得额外处理

到此这篇关于springboot捕获feign抛出异常的方法的文章就介绍到这了,更多相关springboot捕获feign异常内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com