SpringBoot捕獲feign拋出異常的方法
前言
使用Springboot時(shí),使用feign客戶端作為http請(qǐng)求工具時(shí),當(dāng)接口拋出異常信息時(shí),使用全局異常是捕獲不了異常的
feign異常全局捕獲
定義一個(gè)異常類
@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請(qǐng)求異常
@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請(qǐng)求錯(cuò)誤,返回值為:{{}}", 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);
};
}
}
或者在全局異常捕獲加上這個(gè)
@ExceptionHandler(FeignException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public String handleFeignException(FeignException ex) {
log.error("feign異常處理信息", ex);
return ex.contentUTF8();
}
總結(jié)
feign客戶端是一個(gè)強(qiáng)大的請(qǐng)求工具,但是異常處理有時(shí)候得額外處理
到此這篇關(guān)于SpringBoot捕獲feign拋出異常的方法的文章就介紹到這了,更多相關(guān)SpringBoot捕獲feign異常內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Maven?pom.xml文件獲取當(dāng)前時(shí)間戳方式
這篇文章主要介紹了Maven?pom.xml文件獲取當(dāng)前時(shí)間戳方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-12-12
Spring Cloud實(shí)現(xiàn)提供API給客戶端的方法詳解
這篇文章主要給大家介紹了關(guān)于Spring Cloud實(shí)現(xiàn)提供API給客戶端的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2018-01-01
java實(shí)現(xiàn)token無感刷新+處理并發(fā)的后端方案
在Web應(yīng)用中,Token用于身份驗(yàn)證和會(huì)話管理,但當(dāng)Token過期時(shí),可能會(huì)導(dǎo)致用戶在提交表單或進(jìn)行操作時(shí)突然被重定向到登錄頁面,本文就來介紹一下java實(shí)現(xiàn)token無感刷新+處理并發(fā)的后端方案,感興趣的可以了解一下2024-11-11

