SpringBoot捕获feign抛出异常的方法

2025-05-14 10:36:44 169
魁首哥

前言

使用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异常内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

分享
海报
169
上一篇:SpringBoot项目中使用Netty实现远程调用的示例代码 下一篇:Java8如何优雅的记录代码运行时间

忘记密码?

图形验证码