Browse Source

优化feign 异常处理

wuxw 7 years ago
parent
commit
d4e1929dca

+ 20 - 1
java110-core/src/main/java/com/java110/core/feign/FeignConfiguration.java

@@ -1,13 +1,32 @@
 package com.java110.core.feign;
 
+import feign.Feign;
 import feign.codec.ErrorDecoder;
 import org.springframework.context.annotation.Bean;
 import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.Scope;
 
+/**
+ *
+ */
 @Configuration
 public class FeignConfiguration {
+    /**
+     *
+     * @return
+     */
     @Bean
-    public ErrorDecoder errorDecoder(){
+    public ErrorDecoder errorDecoder() {
         return new UserErrorDecoder();
     }
+
+    /**
+     *
+     * @return
+     */
+   /* @Bean
+    @Scope("prototype")
+    public Feign.Builder feignBuilder() {
+        return Feign.builder();
+    }*/
 }

+ 18 - 6
java110-core/src/main/java/com/java110/core/feign/UserErrorDecoder.java

@@ -10,27 +10,39 @@ import org.slf4j.LoggerFactory;
 
 import java.io.IOException;
 
+/**
+ * 自定义异常解析
+ */
 public class UserErrorDecoder implements ErrorDecoder {
 
+    private static final int HTTP_STATUS_400 = 400;
+
     private Logger logger = LoggerFactory.getLogger(getClass());
 
+    /**
+     * 异常解析 在 SynchronousMethodHandler 类 134 号调用
+     *
+     * @param methodKey 方法key
+     * @param response  返回对象
+     * @return 返回异常
+     */
     public Exception decode(String methodKey, Response response) {
 
         Exception exception = null;
         try {
             String json = Util.toString(response.body().asReader());
 
-            logger.error("调用方法出现异常了:"+json);
+            logger.error("调用方法出现异常了:" + json);
             exception = new RuntimeException(json);
         } catch (IOException ex) {
             logger.error(ex.getMessage(), ex);
         }
-        // 这里只封装4开头的请求异常ß
-        if (400 <= response.status() && response.status() < 500){
-            exception = new HystrixBadRequestException("request exception wrapper", exception);
-        }else{
+        // 这里只封装4开头的请求异常ß && response.status() < 500
+        if (HTTP_STATUS_400 <= response.status()) {
+            exception = new HystrixBadRequestException("请求参数错误:", exception);
+        } else {
             logger.error(exception.getMessage(), exception);
         }
         return exception;
     }
-}
+}