我们可以在@FeignClient的fallback或fallbackFactory中引发异常吗?

问题描述 投票:0回答:1
我使用@FeignClient并希望在Feign抛出Exception时做一些逻辑(例如记录异常信息,然后将结果回复到前端。

[我注意到当连接失败或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的callback或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()); }

所以我想知道当我使用callback / callbackFactory时如何引发异常,或者有另一种方法代替callbackFactory来进行“回调”? 

非常感谢

我使用@FeignClient并希望在Feign引发Exception时做一些逻辑(例如记录异常信息),然后将结果回复到前端。我注意到Feign会抛出FeignException ...

spring-cloud hystrix spring-cloud-feign feign
1个回答
0
投票
我从未在后备中做到这一点,我实现了自定义错误解码器(“ CustomFeignErrorDecoder”)类并扩展了feign.codec.ErrorDecoder,每次发生此类错误时,都将涉及到该类。
© www.soinside.com 2019 - 2024. All rights reserved.