Selaa lähdekoodia

处理feign 异常处理

吴学文 7 vuotta sitten
vanhempi
commit
cec5799c7d

+ 5 - 0
java110-core/pom.xml

@@ -61,6 +61,11 @@
             <groupId>org.springframework.cloud</groupId>
             <artifactId>spring-cloud-starter-ribbon</artifactId>
         </dependency>
+        <dependency>
+            <groupId>com.netflix.hystrix</groupId>
+            <artifactId>hystrix-core</artifactId>
+            <scope>provided</scope>
+        </dependency>
 
     </dependencies>
 </project>

+ 13 - 0
java110-core/src/main/java/com/java110/core/feign/FeignConfiguration.java

@@ -0,0 +1,13 @@
+package com.java110.core.feign;
+
+import feign.codec.ErrorDecoder;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+@Configuration
+public class FeignConfiguration {
+    @Bean
+    public ErrorDecoder errorDecoder(){
+        return new UserErrorDecoder();
+    }
+}

+ 36 - 0
java110-core/src/main/java/com/java110/core/feign/UserErrorDecoder.java

@@ -0,0 +1,36 @@
+package com.java110.core.feign;
+
+
+import com.netflix.hystrix.exception.HystrixBadRequestException;
+import feign.Response;
+import feign.Util;
+import feign.codec.ErrorDecoder;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+
+public class UserErrorDecoder implements ErrorDecoder {
+
+    private Logger logger = LoggerFactory.getLogger(getClass());
+
+    public Exception decode(String methodKey, Response response) {
+
+        Exception exception = null;
+        try {
+            String json = Util.toString(response.body().asReader());
+
+            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{
+            logger.error(exception.getMessage(), exception);
+        }
+        return exception;
+    }
+}