zxy hace 2 años
padre
commit
47a53f2a63

+ 25 - 0
src/main/java/com/api/controller/AbsctactController.java

@@ -0,0 +1,25 @@
1
+package com.api.controller;
2
+
3
+import com.common.utils.R;
4
+
5
+public abstract class AbsctactController {
6
+    protected R success() {
7
+        return R.ok();
8
+    }
9
+
10
+    protected R success(String msg) {
11
+        return R.ok(msg);
12
+    }
13
+
14
+    protected R error() {
15
+        return R.error();
16
+    }
17
+
18
+    protected R error(String msg) {
19
+        return R.error(msg);
20
+    }
21
+
22
+    protected R error(String code, String msg) {
23
+        return R.error(code, msg);
24
+    }
25
+}

+ 2 - 2
src/main/java/com/api/controller/ApiLoginController.java

@@ -18,6 +18,7 @@ import com.api.service.UserService;
18 18
 import io.swagger.annotations.Api;
19 19
 import io.swagger.annotations.ApiOperation;
20 20
 import org.springframework.beans.factory.annotation.Autowired;
21
+import org.springframework.context.ApplicationContext;
21 22
 import org.springframework.web.bind.annotation.*;
22 23
 import springfox.documentation.annotations.ApiIgnore;
23 24
 
@@ -31,13 +32,12 @@ import java.util.Map;
31 32
 @RestController
32 33
 @RequestMapping("/api")
33 34
 @Api(tags="登录接口")
34
-public class ApiLoginController {
35
+public class ApiLoginController extends AbsctactController {
35 36
     @Autowired
36 37
     private UserService userService;
37 38
     @Autowired
38 39
     private TokenService tokenService;
39 40
 
40
-
41 41
     @PostMapping("login")
42 42
     @ApiOperation("登录")
43 43
     public R login(@RequestBody LoginForm form){

+ 8 - 2
src/main/java/com/api/controller/ApiTestController.java

@@ -8,12 +8,15 @@
8 8
 
9 9
 package com.api.controller;
10 10
 
11
+import com.api.dao.TokenDao;
11 12
 import com.common.utils.R;
12 13
 import com.api.annotation.Login;
13 14
 import com.api.annotation.LoginUser;
14 15
 import com.api.entity.UserEntity;
15 16
 import io.swagger.annotations.Api;
16 17
 import io.swagger.annotations.ApiOperation;
18
+import org.springframework.beans.factory.annotation.Autowired;
19
+import org.springframework.context.ApplicationContext;
17 20
 import org.springframework.web.bind.annotation.GetMapping;
18 21
 import org.springframework.web.bind.annotation.RequestAttribute;
19 22
 import org.springframework.web.bind.annotation.RequestMapping;
@@ -28,7 +31,9 @@ import springfox.documentation.annotations.ApiIgnore;
28 31
 @RestController
29 32
 @RequestMapping("/api/api")
30 33
 @Api(tags="测试接口")
31
-public class ApiTestController {
34
+public class ApiTestController extends AbsctactController {
35
+    @Autowired
36
+    ApplicationContext applicationContext;
32 37
 
33 38
     @Login
34 39
     @GetMapping("userInfo")
@@ -44,10 +49,11 @@ public class ApiTestController {
44 49
         return R.ok().put("userId", userId);
45 50
     }
46 51
 
47
-    @Login
48 52
     @GetMapping("notToken")
49 53
     @ApiOperation("忽略Token验证测试")
50 54
     public R notToken(){
55
+        Object beanNamesForType = applicationContext.getBeanProvider(TokenDao.class);
56
+        TokenDao tokenDao = (TokenDao) beanNamesForType;
51 57
         return R.ok().put("msg", "无需token也能访问。。。");
52 58
     }
53 59
 

+ 132 - 0
src/main/java/com/common/exception/RRExceptionHandler.java

@@ -0,0 +1,132 @@
1
+package com.common.exception;
2
+
3
+import com.alibaba.fastjson.JSONException;
4
+import com.common.utils.LogUtils;
5
+import com.common.utils.R;
6
+import lombok.extern.slf4j.Slf4j;
7
+import org.springframework.beans.factory.annotation.Autowired;
8
+import org.springframework.dao.DuplicateKeyException;
9
+import org.springframework.http.converter.HttpMessageConversionException;
10
+import org.springframework.http.converter.HttpMessageNotReadableException;
11
+import org.springframework.validation.FieldError;
12
+import org.springframework.web.HttpRequestMethodNotSupportedException;
13
+import org.springframework.web.bind.MethodArgumentNotValidException;
14
+import org.springframework.web.bind.MissingServletRequestParameterException;
15
+import org.springframework.web.bind.annotation.ExceptionHandler;
16
+import org.springframework.web.bind.annotation.RestControllerAdvice;
17
+import org.springframework.web.servlet.NoHandlerFoundException;
18
+
19
+@Slf4j
20
+@RestControllerAdvice
21
+public class RRExceptionHandler {
22
+    @Autowired
23
+    private LogUtils logUtils;
24
+    /**
25
+     * 处理自定义异常
26
+     */
27
+    @ExceptionHandler(RRException.class)
28
+    public R handleRRException(RRException e){
29
+        R r;
30
+//        if (StringUtils.isEmpty(e.getMessage())) {
31
+//            r = R.error();
32
+//        }
33
+        r = R.error(e.getErrno(), e.getErrmsg());
34
+        logUtils.requestLog(r);
35
+        return r;
36
+    }
37
+
38
+    @ExceptionHandler(NoHandlerFoundException.class)
39
+    public R handlerMyNoHandlerFoundException(NoHandlerFoundException e) {
40
+        R r = R.error("404", "路径不存在,请检查路径是否正确");
41
+        logUtils.requestLog(r);
42
+        return r;
43
+    }
44
+
45
+    @ExceptionHandler(DuplicateKeyException.class)
46
+    public R handleDuplicateKeyException(DuplicateKeyException e){
47
+        logUtils.requestLog(e);
48
+        return R.error("数据库中已存在该记录");
49
+    }
50
+
51
+//    @ExceptionHandler(AuthorizationException.class)
52
+//    public R handleAuthorizationException(AuthorizationException e){
53
+//        R r = R.error("没有权限,请联系管理员授权");
54
+//        logUtils.requestLog(r);
55
+//        return r;
56
+//    }
57
+
58
+    /**
59
+     * 处理 @Valid 对 @RequestBody 参数验证异常
60
+     * @param e
61
+     * @return
62
+     */
63
+    @ExceptionHandler(MethodArgumentNotValidException.class)
64
+    public R handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
65
+        FieldError fieldError = e.getBindingResult().getFieldError();
66
+        R r = R.error(fieldError.getField() + fieldError.getDefaultMessage());
67
+        logUtils.requestLog(r);
68
+        return r;
69
+    }
70
+
71
+    /**
72
+     * 参数类型转换错误
73
+     *
74
+     * @param exception 错误
75
+     * @return 错误信息
76
+     */
77
+    @ExceptionHandler(HttpMessageConversionException.class)
78
+    public R parameterTypeException(HttpMessageConversionException exception) {
79
+        R r = R.error(exception.getCause().getLocalizedMessage());
80
+        return  r;
81
+    }
82
+
83
+    /**
84
+     * 处理 @RequestBody 但 body none 异常
85
+     * @param e
86
+     * @return
87
+     */
88
+    @ExceptionHandler(HttpMessageNotReadableException.class)
89
+    public R handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
90
+        String message = e.getMessage();
91
+        R r = R.error(message.substring(0, message.indexOf(":")));
92
+        logUtils.requestLog(message);
93
+        return r;
94
+    }
95
+
96
+    /**
97
+     * 处理 @RequestParam required=true 但未收到值异常
98
+     * @param e
99
+     * @return
100
+     */
101
+    @ExceptionHandler(MissingServletRequestParameterException.class)
102
+    public R handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {
103
+        R r = R.error("缺少参数" + e.getParameterName());
104
+        logUtils.requestLog(r);
105
+        return r;
106
+    }
107
+
108
+    @ExceptionHandler(JSONException.class)
109
+    public R handleJSONException(JSONException e){
110
+//        logUtils.requestLog(e);
111
+        return R.error("数据格式错误");
112
+    }
113
+
114
+    /**
115
+     * 处理请求方法不支持异常
116
+     * @param e
117
+     * @return
118
+     */
119
+    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
120
+    public R handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
121
+        R r = R.error(String.format("当前路径不支持%s请求", e.getMethod()));
122
+        logUtils.requestLog(r);
123
+        return r;
124
+    }
125
+
126
+    @ExceptionHandler(Exception.class)
127
+    public R handleException(Exception e){
128
+        logUtils.requestLog(e);
129
+        e.printStackTrace();
130
+        return R.error();
131
+    }
132
+}

+ 93 - 0
src/main/java/com/common/utils/LogUtils.java

@@ -0,0 +1,93 @@
1
+package com.common.utils;
2
+
3
+import com.alibaba.fastjson.JSON;
4
+import com.alibaba.fastjson.JSONException;
5
+import com.alibaba.fastjson.JSONObject;
6
+import com.alibaba.fastjson.serializer.SerializerFeature;
7
+import lombok.extern.slf4j.Slf4j;
8
+import org.springframework.http.HttpHeaders;
9
+import org.springframework.http.HttpMethod;
10
+import org.springframework.http.MediaType;
11
+import org.springframework.stereotype.Component;
12
+import org.springframework.web.context.request.RequestContextHolder;
13
+import org.springframework.web.context.request.ServletRequestAttributes;
14
+
15
+import javax.servlet.http.HttpServletRequest;
16
+import java.io.BufferedReader;
17
+import java.io.IOException;
18
+import java.util.*;
19
+import java.util.stream.Collectors;
20
+
21
+@Slf4j
22
+@Component
23
+public class LogUtils {
24
+    public static String newLine = System.getProperty("line.separator");
25
+
26
+    private List<String> requestLogCommon() {
27
+        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
28
+        HttpServletRequest request = attributes.getRequest();
29
+
30
+        List<String> logList = new LinkedList<>();
31
+        logList.add("请求日志:");
32
+        logList.add("url=" + request.getRequestURI());
33
+        String accessToken = request.getHeader("access_token");
34
+        logList.add("accessToken=" + accessToken);
35
+        String method = request.getMethod();
36
+        String contentType = request.getHeader(HttpHeaders.CONTENT_TYPE);
37
+        Map<String, String[]> map = request.getParameterMap();
38
+        Map<String, Object> params = new LinkedHashMap<>();
39
+        map.forEach((key, value) -> {
40
+            Object object = value.length == 1 ? value[0] : Arrays.asList(value);
41
+            params.put(key, object);
42
+        });
43
+        logList.add("paramData=" + JSON.toJSONString(params));
44
+        if (HttpMethod.POST.name().equals(method) && null != contentType &&
45
+                contentType.startsWith(MediaType.APPLICATION_JSON_VALUE)) {
46
+            try (BufferedReader br = new BufferedReader(request.getReader())) {
47
+                String paramData = br.readLine();
48
+                logList.add("body=" + paramData);
49
+            } catch (IOException e) {
50
+                e.printStackTrace();
51
+            }
52
+        }
53
+        logList.add("clientIp=" + IPUtils.getIpAddr(request));
54
+        logList.add("HTTP_METHOD=" + method);
55
+
56
+        return logList;
57
+    }
58
+
59
+    public void requestLog(Object result, long costTime) {
60
+        List<String> logList = requestLogCommon();
61
+        logList.add("返回内容:" + JSON.toJSONString(result, SerializerFeature.WriteDateUseDateFormat));
62
+        String resultString = JSON.toJSONString(result);
63
+        try {
64
+            JSONObject resultJson = JSON.parseObject(resultString);
65
+            if (resultJson.containsKey("errno")) {
66
+                Integer errno = resultJson.getInteger("errno");
67
+                if (errno == 0) {
68
+                    logList.add(1, "请求开始:");
69
+                    logList.add("请求耗时:" + costTime);
70
+                    log.info(logList.stream().collect(Collectors.joining(newLine)));
71
+                } else {
72
+                    logList.add(1, "请求错误:");
73
+                    log.warn(logList.stream().collect(Collectors.joining(newLine)));
74
+                }
75
+                return;
76
+            }
77
+        } catch (JSONException e) {
78
+        }
79
+    }
80
+
81
+    public void requestLog(RuntimeException e) {
82
+        if (e != null) {
83
+            List<String> logList = requestLogCommon();
84
+            logList.add(1, "请求异常:");
85
+            logList.add("异常信息:");
86
+            log.error(logList.stream().collect(Collectors.joining(newLine)), e);
87
+        }
88
+    }
89
+
90
+    public void requestLog(Object result) {
91
+        requestLog(result, 0);
92
+    }
93
+}