Explorar o código

优化异常判断

zhouhao %!s(int64=7) %!d(string=hai) anos
pai
achega
8ce42f6e02

+ 26 - 1
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-client/src/main/java/org/hswebframework/web/authorization/oauth2/client/OAuth2ClientAutoConfiguration.java

@@ -1,22 +1,31 @@
 package org.hswebframework.web.authorization.oauth2.client;
 
+import lombok.extern.slf4j.Slf4j;
 import org.hswebframework.expands.request.RequestBuilder;
 import org.hswebframework.expands.request.SimpleRequestBuilder;
 import org.hswebframework.web.authorization.builder.AuthenticationBuilderFactory;
+import org.hswebframework.web.authorization.oauth2.client.exception.OAuth2RequestException;
 import org.hswebframework.web.authorization.oauth2.client.request.DefaultResponseJudge;
 import org.hswebframework.web.authorization.oauth2.client.simple.*;
 import org.hswebframework.web.authorization.oauth2.client.simple.provider.HswebResponseConvertSupport;
 import org.hswebframework.web.authorization.oauth2.client.simple.provider.HswebResponseJudgeSupport;
 import org.hswebframework.web.authorization.oauth2.client.simple.request.builder.SimpleOAuth2RequestBuilderFactory;
 import org.hswebframework.web.concurrent.lock.LockManager;
+import org.hswebframework.web.controller.message.ResponseMessage;
 import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
 import org.springframework.boot.context.properties.ConfigurationProperties;
 import org.springframework.context.annotation.Bean;
+import org.springframework.http.HttpStatus;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.bind.annotation.ResponseBody;
+import org.springframework.web.bind.annotation.ResponseStatus;
+import org.springframework.web.bind.annotation.RestControllerAdvice;
 
 /**
  * @author zhouhao
  * @since 3.0
  */
+@Slf4j
 public class OAuth2ClientAutoConfiguration {
 
     @Bean
@@ -48,7 +57,7 @@ public class OAuth2ClientAutoConfiguration {
             , OAuth2RequestBuilderFactory builderFactory
             , LockManager lockManager) {
 
-        return new SimpleOAuth2RequestService(configRepository, userTokenRepository, builderFactory,lockManager);
+        return new SimpleOAuth2RequestService(configRepository, userTokenRepository, builderFactory, lockManager);
     }
 
     @ConditionalOnMissingBean(OAuth2ServerConfigRepository.class)
@@ -63,4 +72,20 @@ public class OAuth2ClientAutoConfiguration {
     public MemoryOAuth2UserTokenRepository memoryOAuth2UserTokenRepository() {
         return new MemoryOAuth2UserTokenRepository();
     }
+
+    @Bean
+    public OAuth2RequestExceptionTranslator oAuth2RequestExceptionTranslator() {
+        return new OAuth2RequestExceptionTranslator();
+    }
+
+    @RestControllerAdvice
+    public static class OAuth2RequestExceptionTranslator {
+        @ExceptionHandler(OAuth2RequestException.class)
+        @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
+        @ResponseBody
+        ResponseMessage handleException(OAuth2RequestException exception) {
+            log.error("oauth2 request error: {} ", exception.getMessage());
+            return ResponseMessage.error(500, exception.getMessage());
+        }
+    }
 }

+ 10 - 5
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-client/src/main/java/org/hswebframework/web/authorization/oauth2/client/simple/provider/HswebResponseConvertSupport.java

@@ -33,8 +33,7 @@ import org.hswebframework.web.oauth2.core.ErrorType;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Component;
 
-import java.util.Collection;
-import java.util.List;
+import java.util.*;
 import java.util.function.Function;
 import java.util.stream.Collectors;
 
@@ -50,12 +49,15 @@ public class HswebResponseConvertSupport implements ResponseConvertForProviderDe
 
     Function<Object, Authentication> autzParser = obj -> convertAuthentication(JSON.toJSONString(obj));
 
+    private static final Set<String> springMvcErrorResponseKeys =
+            new HashSet<>(Arrays.asList("exception", "path", "error", "message", "timestamp", "status"));
+
     public HswebResponseConvertSupport(AuthenticationBuilderFactory authenticationBuilderFactory) {
         this.authenticationBuilderFactory = authenticationBuilderFactory;
     }
 
 
-    public Object tryConvertToObject(String json, Class type) {
+    public Object tryConvertToObject(String json, Class type, OAuth2Response response) {
         if (json.startsWith("{")) {
             if (ResponseMessage.class.isAssignableFrom(type)) {
                 return JSON.parseObject(json, type);
@@ -90,6 +92,9 @@ public class HswebResponseConvertSupport implements ResponseConvertForProviderDe
                 //return data;
                 return message.getObject("result", type);
             }
+            if (springMvcErrorResponseKeys.containsAll(message.keySet())) {
+                throw new OAuth2RequestException(ErrorType.SERVICE_ERROR, response);
+            }
             return message.toJavaObject(type);
         } else if (json.startsWith("[")) {
             if (type == Authentication.class) {
@@ -112,7 +117,7 @@ public class HswebResponseConvertSupport implements ResponseConvertForProviderDe
     public <T> T convert(OAuth2Response response, Class<T> type) {
         String json = response.asString();
 
-        Object data = tryConvertToObject(json, type);
+        Object data = tryConvertToObject(json, type, response);
         if (null == data) return null;
         if (type.isInstance(data)) {
             //success
@@ -132,7 +137,7 @@ public class HswebResponseConvertSupport implements ResponseConvertForProviderDe
     public <T> List<T> convertList(OAuth2Response response, Class<T> type) {
         String json = response.asString();
 
-        Object data = tryConvertToObject(json, type);
+        Object data = tryConvertToObject(json, type, response);
         if (null == data) return null;
         if (data instanceof List) {
             //success

+ 65 - 0
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-client/src/test/java/org/hswebframework/web/authorization/oauth2/client/simple/provider/HswebResponseConvertSupportTest.java

@@ -0,0 +1,65 @@
+package org.hswebframework.web.authorization.oauth2.client.simple.provider;
+
+import org.hswebframework.web.BusinessException;
+import org.hswebframework.web.authorization.oauth2.client.exception.OAuth2RequestException;
+import org.hswebframework.web.authorization.simple.builder.SimpleAuthenticationBuilderFactory;
+import org.hswebframework.web.authorization.simple.builder.SimpleDataAccessConfigBuilderFactory;
+import org.hswebframework.web.controller.message.ResponseMessage;
+import org.junit.Assert;
+import org.junit.Test;
+
+import java.math.BigDecimal;
+
+import static org.junit.Assert.*;
+
+/**
+ * TODO 完成注释
+ *
+ * @author zhouhao
+ * @since
+ */
+public class HswebResponseConvertSupportTest {
+
+    private HswebResponseConvertSupport convertSupport = new HswebResponseConvertSupport(new SimpleAuthenticationBuilderFactory(new SimpleDataAccessConfigBuilderFactory()));
+
+
+    @Test
+    public void testConvertSpringError() {
+        String str = "{\"exception\":\"java.lang.RuntimeException\",\"path\":\"/file/upload-static\",\"error\":\"Internal Server Error\",\"message\":\"java.nio.file.FileSystemException: /tmp/undertow8543459739529410666upload: No space left on device\",\"timestamp\":\"2018-01-09 20:22:07\",\"status\":500}";
+        try {
+            convertSupport.convert(new MockOAuth2Response(str), String.class);
+            Assert.assertTrue(false);
+        } catch (OAuth2RequestException e) {
+            // is ok
+        }
+    }
+
+    @Test
+    public void testConvertHswebError() {
+        String str = ResponseMessage.error("test").toString();
+        try {
+            convertSupport.convert(new MockOAuth2Response(str), String.class);
+            Assert.assertTrue(false);
+        } catch (BusinessException e) {
+            // is ok
+        }
+    }
+
+    @Test
+    public void testConvertHswebResponse() {
+        String str = ResponseMessage.ok("test").toString();
+        String res = convertSupport.convert(new MockOAuth2Response(str), String.class);
+        Assert.assertEquals(res, "test");
+
+        str = ResponseMessage.ok(1).toString();
+        Assert.assertEquals((Object) convertSupport.convert(new MockOAuth2Response(str), Integer.class), 1);
+
+        str = ResponseMessage.ok(true).toString();
+        Assert.assertTrue(convertSupport.convert(new MockOAuth2Response(str), Boolean.class));
+
+        str = ResponseMessage.ok("999999999999999999").toString();
+        Assert.assertEquals(convertSupport.convert(new MockOAuth2Response(str), BigDecimal.class), new BigDecimal("999999999999999999"));
+
+    }
+
+}

+ 66 - 0
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-client/src/test/java/org/hswebframework/web/authorization/oauth2/client/simple/provider/MockOAuth2Response.java

@@ -0,0 +1,66 @@
+package org.hswebframework.web.authorization.oauth2.client.simple.provider;
+
+import org.hswebframework.web.authorization.oauth2.client.request.ResponseConvertHandler;
+import org.hswebframework.web.authorization.oauth2.client.response.OAuth2Response;
+import org.hswebframework.web.authorization.oauth2.client.response.ResponseConvert;
+import org.hswebframework.web.authorization.oauth2.client.simple.provider.HswebResponseConvertSupport;
+import org.hswebframework.web.authorization.simple.builder.SimpleAuthenticationBuilderFactory;
+import org.hswebframework.web.authorization.simple.builder.SimpleDataAccessConfigBuilderFactory;
+import org.hswebframework.web.oauth2.core.ErrorType;
+
+import java.io.ByteArrayInputStream;
+import java.io.InputStream;
+import java.util.List;
+import java.util.function.BiConsumer;
+
+public class MockOAuth2Response implements OAuth2Response {
+
+    private String result;
+
+    private ResponseConvertHandler handler = new HswebResponseConvertSupport(new SimpleAuthenticationBuilderFactory(new SimpleDataAccessConfigBuilderFactory()));
+
+
+    @Override
+    public InputStream asStream() {
+        return new ByteArrayInputStream(result.getBytes());
+    }
+
+    public MockOAuth2Response(String result) {
+        this.result = result;
+    }
+
+    @Override
+    public String asString() {
+        return result;
+    }
+
+    @Override
+    public byte[] asBytes() {
+        return result.getBytes();
+    }
+
+    @Override
+    public <T> T as(ResponseConvert<T> convert) {
+        return convert.convert(this);
+    }
+
+    @Override
+    public <T> T as(Class<T> type) {
+        return handler.convert(this, type);
+    }
+
+    @Override
+    public <T> List<T> asList(Class<T> type) {
+        return handler.convertList(this, type);
+    }
+
+    @Override
+    public int status() {
+        return 200;
+    }
+
+    @Override
+    public OAuth2Response onError(BiConsumer<OAuth2Response, ErrorType> onError) {
+        return this;
+    }
+}

+ 10 - 0
hsweb-starter/hsweb-spring-boot-starter/src/main/java/org/hswebframework/web/starter/RestControllerExceptionTranslator.java

@@ -110,6 +110,16 @@ public class RestControllerExceptionTranslator {
 
         return ResponseMessage.error(400, results.getResults().size() == 0 ? e.getMessage() : results.getResults().get(0).getMessage()).result(results.getResults());
     }
+
+    @ExceptionHandler(RuntimeException.class)
+    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
+    @ResponseBody
+    ResponseMessage handleException(RuntimeException exception) {
+        logger.error(exception.getMessage(), exception);
+        return ResponseMessage.error(400, exception.getMessage());
+    }
+
+
 //    @ExceptionHandler(Throwable.class)
 //    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
 //    @ResponseBody