当前位置:   article > 正文

Feign调用接口如何处理内部异常_feign调用接口捕获异常

feign调用接口捕获异常

问题描述:当使用feign调用接口,出现400~500~的接口问题时。会出错feign:FeignException。(因为是错误,只能用catch Throwable,不可使用catch Exception捕获异常)导致程序无法继续运行。

问题原因:由于feign默认的错误处理类是FunFeignFallback会throw new AfsBaseExceptio导致外部无法捕获异常。

  1. import com.alibaba.fastjson.JSONObject;
  2. import com.ruicar.afs.cloud.common.core.exception.AfsBaseException;
  3. import com.ruicar.afs.cloud.common.core.util.IResponse;
  4. import feign.FeignException;
  5. import lombok.AllArgsConstructor;
  6. import lombok.Data;
  7. import lombok.extern.slf4j.Slf4j;
  8. import org.springframework.cglib.proxy.MethodInterceptor;
  9. import org.springframework.cglib.proxy.MethodProxy;
  10. import org.springframework.lang.Nullable;
  11. import java.lang.reflect.Method;
  12. import java.util.Objects;
  13. @Data
  14. @AllArgsConstructor
  15. @Slf4j
  16. public class FunFeignFallback<T> implements MethodInterceptor {
  17. private final Class<T> targetType;
  18. private final String targetName;
  19. private final Throwable cause;
  20. private static byte JSON_START = '{';
  21. @Nullable
  22. @Override
  23. public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
  24. String errorMessage = cause.getMessage();
  25. if (!(cause instanceof FeignException)) {
  26. log.error("FunFeignFallback:[{}.{}] serviceId:[{}] message:[{}]", targetType.getName(), method.getName(), targetName, errorMessage);
  27. log.error("feign调用失败", cause);
  28. return IResponse.fail("请求失败,请稍后再试");
  29. }
  30. int status = ((FeignException.FeignClientException) this.cause).status();
  31. boolean isAuthFail = (status==426||status==403||status==401)&&"afs-auth".equals(targetName);
  32. FeignException exception = (FeignException) cause;
  33. if(isAuthFail){
  34. log.warn("授权失败==========原始返回信息:[{}]",exception.contentUTF8());
  35. }else {
  36. log.error("FunFeignFallback:[{}.{}] serviceId:[{}] message:[{}]", targetType.getName(), method.getName(), targetName, errorMessage);
  37. log.error("", cause);
  38. log.error("原始返回信息{}",exception.contentUTF8());
  39. }
  40. if(method.getReturnType().equals(Void.class)){
  41. throw new AfsBaseException("接口调用失败");
  42. }
  43. if(method.getReturnType().equals(IResponse.class)){
  44. if(exception instanceof FeignException.Forbidden){
  45. return IResponse.fail("没有权限").setCode("403");
  46. }
  47. if(exception instanceof FeignException.NotFound){
  48. return IResponse.fail("请求路径不存在").setCode("404");
  49. }
  50. if(exception instanceof FeignException.BadRequest){
  51. return IResponse.fail("参数错误").setCode("400");
  52. }
  53. if(exception.content()==null||exception.content().length==0){
  54. return IResponse.fail("请求失败,请稍后再试");
  55. }
  56. if(JSON_START==exception.content()[0]){
  57. return JSONObject.parseObject(exception.content(),IResponse.class);
  58. }else{
  59. return IResponse.fail(exception.contentUTF8());
  60. }
  61. }else{
  62. try {
  63. if(method.getReturnType().equals(String.class)){
  64. return exception.contentUTF8();
  65. }else if(method.getReturnType().equals(JSONObject.class)){
  66. if(JSON_START==exception.content()[0]){
  67. return JSONObject.parseObject(exception.content(), JSONObject.class);
  68. }
  69. }else if(!method.getReturnType().equals(Object.class)){
  70. return JSONObject.parseObject(exception.content(), method.getReturnType());
  71. }
  72. if(JSON_START==exception.content()[0]){
  73. JSONObject jsonObject = JSONObject.parseObject(exception.content(), JSONObject.class);
  74. if(jsonObject.containsKey("code")&&jsonObject.containsKey("msg")) {
  75. return jsonObject.toJavaObject(IResponse.class);
  76. }
  77. }
  78. }catch (Throwable e){}
  79. throw new AfsBaseException("接口调用失败");
  80. }
  81. }
  82. @Override
  83. public boolean equals(Object o) {
  84. if (this == o) {
  85. return true;
  86. }
  87. if (o == null || getClass() != o.getClass()) {
  88. return false;
  89. }
  90. FunFeignFallback<?> that = (FunFeignFallback<?>) o;
  91. return targetType.equals(that.targetType);
  92. }
  93. @Override
  94. public int hashCode() {
  95. return Objects.hash(targetType);
  96. }
  97. }

问题解决:自定义feignFallback异常处理:

1.自定义异常处理 InvoiceApiFeignFallbackFactory

  1. @Component
  2. public class InvoiceApiFeignFallbackFactory implements FallbackFactory<InvoiceApiFeign> {
  3. @Override
  4. public InvoiceApiFeign create(Throwable throwable) {
  5. InvoiceApiFeignFallback invoiceApiFeignFallback = new InvoiceApiFeignFallback();
  6. invoiceApiFeignFallback.setCause(throwable);
  7. return invoiceApiFeignFallback;
  8. }
  9. }

2.feign调用 InvoiceApiFeignFallbackFactory

  1. /**
  2. * @description:
  3. * @author:
  4. * @date: 2020/8/14 10:32
  5. */
  6. @FeignClient(name = "invoice", url = "${}" ,fallbackFactory = InvoiceApiFeignFallbackFactory.class)
  7. public interface InvoiceApiFeign {
  8. /**
  9. *
  10. * @param dto
  11. * @return
  12. */
  13. @ApiOperation("获取业务数据API接口")
  14. @PostMapping(value = "/vi/check")
  15. @AfsFeignClear(true)//通过此注解防止添加内部token
  16. JSONObject InvoiceCheck(@RequestBody InvoiceCheckDto dto, @RequestHeader Map<String, String> headers);
  17. }

3.实现自定义报错处理

  1. /**
  2. * @author
  3. * @date
  4. */
  5. @Slf4j
  6. @Component
  7. public class InvoiceApiFeignFallback implements InvoiceApiFeign {
  8. @Setter
  9. private Throwable cause;
  10. /**
  11. * @param dto
  12. * @param headers
  13. * @return
  14. */
  15. @Override
  16. public JSONObject InvoiceCheck(InvoiceCheckDto dto, Map<String, String> headers) {
  17. log.error("feign 接口调用失败", cause);
  18. return null;
  19. }
  20. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/84599
推荐阅读
相关标签
  

闽ICP备14008679号