Kaynağa Gözat

feat(在全局异常拦截器中增加两类异常处理): 1、请求路径中缺少必需的路径变量;2、请求参数类型不匹配

otto 2 yıl önce
ebeveyn
işleme
924aafae86

+ 22 - 0
ruoyi-common/ruoyi-common-security/src/main/java/com/ruoyi/common/security/handler/GlobalExceptionHandler.java

@@ -6,6 +6,7 @@ import org.slf4j.LoggerFactory;
6 6
 import org.springframework.validation.BindException;
7 7
 import org.springframework.web.HttpRequestMethodNotSupportedException;
8 8
 import org.springframework.web.bind.MethodArgumentNotValidException;
9
+import org.springframework.web.bind.MissingPathVariableException;
9 10
 import org.springframework.web.bind.annotation.ExceptionHandler;
10 11
 import org.springframework.web.bind.annotation.RestControllerAdvice;
11 12
 import com.ruoyi.common.core.constant.HttpStatus;
@@ -16,6 +17,7 @@ import com.ruoyi.common.core.exception.auth.NotPermissionException;
16 17
 import com.ruoyi.common.core.exception.auth.NotRoleException;
17 18
 import com.ruoyi.common.core.utils.StringUtils;
18 19
 import com.ruoyi.common.core.web.domain.AjaxResult;
20
+import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
19 21
 
20 22
 /**
21 23
  * 全局异常处理器
@@ -73,6 +75,26 @@ public class GlobalExceptionHandler
73 75
     }
74 76
 
75 77
     /**
78
+     * 请求路径中缺少必需的路径变量
79
+     */
80
+    @ExceptionHandler(MissingPathVariableException.class)
81
+    public AjaxResult handleMissingPathVariableException(MissingPathVariableException e, HttpServletRequest request) {
82
+        String requestURI = request.getRequestURI();
83
+        log.error("请求路径中缺少必需的路径变量'{}',发生系统异常.", requestURI, e);
84
+        return AjaxResult.error(String.format("请求路径中缺少必需的路径变量[%s]", e.getVariableName()));
85
+    }
86
+
87
+    /**
88
+     * 请求参数类型不匹配
89
+     */
90
+    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
91
+    public AjaxResult handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e, HttpServletRequest request) {
92
+        String requestURI = request.getRequestURI();
93
+        log.error("请求参数类型不匹配'{}',发生系统异常.", requestURI, e);
94
+        return AjaxResult.error(String.format("请求参数类型不匹配,参数[%s]要求类型为:'%s',但输入值为:'%s'", e.getName(), e.getRequiredType().getName(), e.getValue()));
95
+    }
96
+
97
+    /**
76 98
      * 拦截未知的运行时异常
77 99
      */
78 100
     @ExceptionHandler(RuntimeException.class)