SpringBoot捕获feign抛出异常的方法
更新时间:2025年04月20日 09:31:01 作者:考虑考虑
使用Springboot时,使用feign客户端作为http请求工具时,当接口抛出异常信息时,使用全局异常是捕获不了异常的,本文小编给大家介绍了SpringBoot捕获feign抛出异常的方法,需要的朋友可以参考下
前言
使用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异常内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
java同步器AQS架构AbstractQueuedSynchronizer原理解析
这篇文章主要为大家介绍了java同步器AQS架构AbstractQueuedSynchronizer的底层原理及源码解析,有需要的朋友可以借鉴参考下,希望能有所帮助,祝大家多多进步早日升职加薪2022-03-03
Java报错Java.text.ParseException的解决方法汇总
在Java开发的复杂世界中,错误处理是开发者必须面对的关键挑战之一,其中,Java.text.ParseException就像一个隐藏在代码丛林中的陷阱,常常让开发者们陷入困惑,本文给大家介绍了Java报错Java.text.ParseException的解决方法,需要的朋友可以参考下2024-10-10
java根据当前时间获取yyyy-MM-dd HH:mm:ss标准格式的时间代码示例
在Java中可以使用java.time包中的LocalDateTime类和DateTimeFormatter类来获取并格式化当前时间为yyyy-MM-dd HH:mm:ss的格式,文中通过代码介绍的非常详细,需要的朋友可以参考下2024-10-10
解决maven打包排除类不生效maven-compiler-plugin问题
总结:在Spring Boot项目B中作为项目A的依赖时,排除启动类不生效的原因是被其他类引用或父POM引入,解决方法是跳过test编译或注释掉@SpringBootTest(classes={BApplication.class})2024-11-11


最新评论