【发布时间】:2020-04-24 20:23:48
【问题描述】:
我正在使用@FeignClient,想在Feign抛出异常时做一些逻辑(比如记录异常信息),然后将结果回复给前端。
我注意到当连接失败或 http 状态不期望时,Feign 会抛出 FeignException。
所以我定义了一个@ExceptionHandler 来在回调方法被调用后捕获FeignException。
@ExceptionHandler(value = FeignException.class)
@ResponseBody
public ResponseResult feignException(FeignException exception){
String message = exception.getMessage();
byte[] content = exception.content();
int status = exception.status();
if(content!=null){
String response=new String(content);
message=String.format("%s response message : %s",message,response);
}
log.warn("{} : {} , cause by : {}",exception.getClass().getSimpleName(),message,exception.getCause());
return ResponseResult.fail(HttpStatus.valueOf(status),String.format("9%s00",status),message);
但是当我设置@FeignClient的回调或者callbackFactory的时候就捕捉不到了。
@FeignClient(url = "${onboardingcase.uri}",name = "OnBoardingCaseService",
fallbackFactory = OnBoardingCaseServiceFallBack.class)
@Component
@Slf4j
public class OnBoardingCaseServiceFallBack implements FallbackFactory<OnBoardingCaseService> {
@Override
public OnBoardingCaseService create(Throwable throwable) {
return new OnBoardingCaseService() {
@Override
public OnBoardingCaseVo query(String coid) {
if(throwable instanceof FeignException){
throw (FeignException)throwable;
}
return null;
}
};
}
}
我注意到是因为 hystrix 接管了这个方法。并且会在 HystrixInvocationHandler 中捕获异常。
try {
Object fallback = HystrixInvocationHandler.this.fallbackFactory.create(this.getExecutionException());
Object result = ((Method)HystrixInvocationHandler.this.fallbackMethodMap.get(method)).invoke(fallback, args);
if (HystrixInvocationHandler.this.isReturnsHystrixCommand(method)) {
return ((HystrixCommand)result).execute();
} else if (HystrixInvocationHandler.this.isReturnsObservable(method)) {
return ((Observable)result).toBlocking().first();
} else if (HystrixInvocationHandler.this.isReturnsSingle(method)) {
return ((Single)result).toObservable().toBlocking().first();
} else if (HystrixInvocationHandler.this.isReturnsCompletable(method)) {
((Completable)result).await();
return null;
} else {
return HystrixInvocationHandler.this.isReturnsCompletableFuture(method) ? ((Future)result).get() : result;
}
} catch (IllegalAccessException var3) {
throw new AssertionError(var3);
} catch (ExecutionException | InvocationTargetException var4) {
throw new AssertionError(var4.getCause());
} catch (InterruptedException var5) {
Thread.currentThread().interrupt();
throw new AssertionError(var5.getCause());
}
所以我想知道当我使用回调/回调工厂时如何抛出异常,或者有另一种方法来代替回调工厂来执行“回调”?
非常感谢
【问题讨论】:
标签: spring-cloud hystrix spring-cloud-feign feign