Browse Source

feat:自定义异常租户数据源异常类,全局拦截异常。

韩帛霖 1 year ago
parent
commit
16b07b5db6

+ 7 - 8
ruoyi-admin/src/main/java/com/ruoyi/web/controller/dragForm/CommonController.java

@@ -25,7 +25,6 @@ import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 
-@Anonymous
 @RestController
 @RequestMapping("/dragform/common")
 public class CommonController extends BaseController {
@@ -43,7 +42,7 @@ public class CommonController extends BaseController {
      * 共通查询
      */
     @GetMapping("/selectList")
-    public TableDataInfo selectList(CommonEntity commonEntity) {
+    public TableDataInfo selectList(CommonEntity commonEntity) throws Exception {
         startPage();
         return getDataTable(commonService.selectList(commonEntity));
     }
@@ -52,7 +51,7 @@ public class CommonController extends BaseController {
      * 共通批量新增
      */
     @PostMapping("/batchInsert")
-    public AjaxResult batchInsert(@RequestBody CommonEntity commonEntity) {
+    public AjaxResult batchInsert(@RequestBody CommonEntity commonEntity) throws Exception {
         return toAjax(commonService.batchInsert(commonEntity));
     }
 
@@ -60,7 +59,7 @@ public class CommonController extends BaseController {
      * 共通修改sql
      */
     @PutMapping("/batchEdit")
-    public AjaxResult edit(@RequestBody CommonEntity commonEntity) {
+    public AjaxResult edit(@RequestBody CommonEntity commonEntity) throws Exception {
         return toAjax(commonService.edit(commonEntity));
     }
 
@@ -68,7 +67,7 @@ public class CommonController extends BaseController {
      * 批量删除
      */
     @DeleteMapping("/batchDelete")
-    public AjaxResult batchDelete(@RequestBody CommonEntity commonEntity) {
+    public AjaxResult batchDelete(@RequestBody CommonEntity commonEntity) throws Exception {
         return toAjax(commonService.batchDelete(commonEntity));
     }
 
@@ -79,7 +78,7 @@ public class CommonController extends BaseController {
      * @return
      */
     @GetMapping("/getTableList")
-    public TableDataInfo queryTableList(CommonEntity commonEntity) {
+    public TableDataInfo queryTableList(CommonEntity commonEntity)  {
         TableSql tableSql = iTableSqlService.selectTableSqlByTSqlKey(commonEntity.getQueryMap().get("sqlkey").toString());
         startPage();  // 校验是否sqlserver 否执行 是执行另一种方式的分页
         return getDataTable(commonService.queryTableList(commonEntity, tableSql));
@@ -109,7 +108,7 @@ public class CommonController extends BaseController {
      * 通用动态表单详情
      */
     @GetMapping("/dragTableInfo")
-    public AjaxResult dragTableInfo(CommonEntity commonEntity) {
+    public AjaxResult dragTableInfo(CommonEntity commonEntity) throws Exception {
         return AjaxResult.success(dragTableService.dragTableInfo(commonEntity.getQueryMap().get("sqlkey").toString()));
     }
 
@@ -117,7 +116,7 @@ public class CommonController extends BaseController {
      * 动态表单预览接口
      */
     @GetMapping("/dragTablePreview")
-    public TableDataInfo DragTablePreview(CommonEntity commonEntity) {
+    public TableDataInfo DragTablePreview(CommonEntity commonEntity) throws Exception {
         startPage();
         return getDataTable(commonService.dragTablePreview(commonEntity));
     }

+ 7 - 3
ruoyi-common/src/main/java/com/ruoyi/common/constant/HttpStatus.java

@@ -2,11 +2,10 @@ package com.ruoyi.common.constant;
 
 /**
  * 返回状态码
- * 
+ *
  * @author ruoyi
  */
-public class HttpStatus
-{
+public class HttpStatus {
     /**
      * 操作成功
      */
@@ -91,4 +90,9 @@ public class HttpStatus
      * 系统警告消息
      */
     public static final int WARN = 601;
+
+    /**
+     * 系统警告消息:数据源信息未找到!认证失败。
+     */
+    public static final int ERRORWARN = 602;
 }

+ 31 - 0
ruoyi-common/src/main/java/com/ruoyi/common/exception/tenantdatassource/TenantDataSource.java

@@ -0,0 +1,31 @@
+package com.ruoyi.common.exception.tenantdatassource;
+
+import com.ruoyi.common.core.domain.AjaxResult;
+
+/**
+ * @author hanzihang
+ * @date 2023/9/20 5:16
+ */
+public class TenantDataSource extends RuntimeException {
+
+    public TenantDataSource() {
+        super();
+    }
+
+    public TenantDataSource(String message) {
+        super(message);
+    }
+
+    public TenantDataSource(String message, Throwable cause) {
+        super(message, cause);
+    }
+
+    public TenantDataSource(Throwable cause) {
+        super(cause);
+    }
+
+    public TenantDataSource(Object message, Object code) {
+        super(message.toString());
+    }
+
+}

+ 4 - 1
ruoyi-common/src/main/java/com/ruoyi/common/utils/SecurityUtils.java

@@ -1,5 +1,6 @@
 package com.ruoyi.common.utils;
 
+import com.ruoyi.common.exception.tenantdatassource.TenantDataSource;
 import org.springframework.security.core.Authentication;
 import org.springframework.security.core.context.SecurityContextHolder;
 import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
@@ -53,7 +54,9 @@ public class SecurityUtils {
         try {
             return getLoginUser().getUser().getTenant().getDataSource().getDatabaseType();
         } catch (Exception e) {
-            throw new ServiceException("获取获取数据源类型异常", HttpStatus.UNAUTHORIZED);
+            return "error";
+            //            System.out.println("获取获取数据源类型异常:" + HttpStatus.ERRORWARN);
+//            throw new TenantDataSource("获取获取数据源类型异常", HttpStatus.ERRORWARN);
         }
     }
 

+ 28 - 14
ruoyi-framework/src/main/java/com/ruoyi/framework/aspectj/SqlInterceptor.java

@@ -1,11 +1,18 @@
 package com.ruoyi.framework.aspectj;
 
+import com.alibaba.fastjson2.JSON;
+import com.ruoyi.common.core.domain.AjaxResult;
+import com.ruoyi.common.exception.tenantdatassource.TenantDataSource;
 import com.ruoyi.common.utils.SecurityUtils;
+import com.ruoyi.common.utils.ServletUtils;
+import com.ruoyi.common.utils.StringUtils;
 import com.ruoyi.common.utils.reflect.ReflectUtils;
+import com.ruoyi.framework.web.service.TokenService;
 import org.apache.ibatis.executor.statement.StatementHandler;
 import org.apache.ibatis.plugin.*;
 import org.aspectj.lang.annotation.Before;
 
+import java.lang.reflect.InvocationTargetException;
 import java.sql.Connection;
 import java.util.Properties;
 
@@ -25,19 +32,31 @@ public class SqlInterceptor implements Interceptor {
         String sql = statementHandler.getBoundSql().getSql();
         // 修改SQL语句
         String modifiedSql = BeforeSQL(sql);
-        // 将修改后的SQL语句设置回StatementHandler
-        ReflectUtils.setFieldValue(statementHandler.getBoundSql(), "sql", modifiedSql);
-        invocation.proceed();
-        ReflectUtils.setFieldValue(statementHandler.getBoundSql(), "sql", sql);
-        return invocation.proceed();
+        if (modifiedSql.equals("error")) {
+            // 终止程序
+            throw new TenantDataSource("租户异常");
+        } else {
+            // 将修改后的SQL语句设置回StatementHandler
+            ReflectUtils.setFieldValue(statementHandler.getBoundSql(), "sql", modifiedSql);
+            invocation.proceed();
+            ReflectUtils.setFieldValue(statementHandler.getBoundSql(), "sql", sql);
+            return invocation.proceed();
+        }
     }
 
     // 根据类型设置不同的选择数据源格式
     private String modifySql(String sql) {
         try {
+            /**
+             * 如何当前请求中并不携带该用户的数据源信息
+             * 分两种情况:
+             * 1.当前用户并没有数据源信息(例如:admin并没有从库数据源信息)
+             * 2.当前用户的token失效(理论上在客户端发送请求时会携带token,逻辑代码执行前会首先验证token的有效性)
+             * 几乎不会出现第二种情况
+             */
             SecurityUtils.getDatabaseType();
         } catch (Exception e) {
-            return sql;
+            return "error";
         }
         if (SecurityUtils.getDatabaseType().equals("sqlserver"))
             return "USE `" + SecurityUtils.getDatabaseName() + "`; " + sql;
@@ -45,24 +64,19 @@ public class SqlInterceptor implements Interceptor {
             return "set schema " + SecurityUtils.getDatabaseName() + "; " + sql;
         if (SecurityUtils.getDatabaseType().equals("mysql"))
             return "USE `" + SecurityUtils.getDatabaseName() + "`; " + sql;
-        return sql;
+        return "error";
     }
 
     // 根据类型设置不同的选择数据源格式
     private String BeforeSQL(String sql) {
-        try {
-            SecurityUtils.getDatabaseType();
-        } catch (Exception e) {
-            // 如果当前请求携带信息异常,返回前端提示重新登录。
-            return "";
-        }
         if (SecurityUtils.getDatabaseType().equals("sqlserver"))
             return "USE `" + SecurityUtils.getDatabaseName() + "`; ";
         if (SecurityUtils.getDatabaseType().equals("dm"))
             return "set schema " + SecurityUtils.getDatabaseName() + "; ";
         if (SecurityUtils.getDatabaseType().equals("mysql"))
             return "USE `" + SecurityUtils.getDatabaseName() + "`; ";
-        return sql;
+        // 如果当前请求携带信息异常,返回前端提示重新登录。
+        return SecurityUtils.getDatabaseType();
     }
 
 

+ 21 - 19
ruoyi-framework/src/main/java/com/ruoyi/framework/web/exception/GlobalExceptionHandler.java

@@ -1,6 +1,7 @@
 package com.ruoyi.framework.web.exception;
 
 import javax.servlet.http.HttpServletRequest;
+
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.security.access.AccessDeniedException;
@@ -15,22 +16,21 @@ import com.ruoyi.common.exception.DemoModeException;
 import com.ruoyi.common.exception.ServiceException;
 import com.ruoyi.common.utils.StringUtils;
 
+
 /**
  * 全局异常处理器
- * 
+ *
  * @author ruoyi
  */
 @RestControllerAdvice
-public class GlobalExceptionHandler
-{
+public class GlobalExceptionHandler {
     private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
 
     /**
      * 权限校验异常
      */
     @ExceptionHandler(AccessDeniedException.class)
-    public AjaxResult handleAccessDeniedException(AccessDeniedException e, HttpServletRequest request)
-    {
+    public AjaxResult handleAccessDeniedException(AccessDeniedException e, HttpServletRequest request) {
         String requestURI = request.getRequestURI();
         log.error("请求地址'{}',权限校验失败'{}'", requestURI, e.getMessage());
         return AjaxResult.error(HttpStatus.FORBIDDEN, "没有权限,请联系管理员授权");
@@ -41,8 +41,7 @@ public class GlobalExceptionHandler
      */
     @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
     public AjaxResult handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e,
-            HttpServletRequest request)
-    {
+                                                          HttpServletRequest request) {
         String requestURI = request.getRequestURI();
         log.error("请求地址'{}',不支持'{}'请求", requestURI, e.getMethod());
         return AjaxResult.error(e.getMessage());
@@ -52,8 +51,7 @@ public class GlobalExceptionHandler
      * 业务异常
      */
     @ExceptionHandler(ServiceException.class)
-    public AjaxResult handleServiceException(ServiceException e, HttpServletRequest request)
-    {
+    public AjaxResult handleServiceException(ServiceException e, HttpServletRequest request) {
         log.error(e.getMessage(), e);
         Integer code = e.getCode();
         return StringUtils.isNotNull(code) ? AjaxResult.error(code, e.getMessage()) : AjaxResult.error(e.getMessage());
@@ -63,8 +61,7 @@ public class GlobalExceptionHandler
      * 拦截未知的运行时异常
      */
     @ExceptionHandler(RuntimeException.class)
-    public AjaxResult handleRuntimeException(RuntimeException e, HttpServletRequest request)
-    {
+    public AjaxResult handleRuntimeException(RuntimeException e, HttpServletRequest request) {
         String requestURI = request.getRequestURI();
         log.error("请求地址'{}',发生未知异常.", requestURI, e);
         return AjaxResult.error(e.getMessage());
@@ -74,8 +71,7 @@ public class GlobalExceptionHandler
      * 系统异常
      */
     @ExceptionHandler(Exception.class)
-    public AjaxResult handleException(Exception e, HttpServletRequest request)
-    {
+    public AjaxResult handleException(Exception e, HttpServletRequest request) {
         String requestURI = request.getRequestURI();
         log.error("请求地址'{}',发生系统异常.", requestURI, e);
         return AjaxResult.error(e.getMessage());
@@ -85,8 +81,7 @@ public class GlobalExceptionHandler
      * 自定义验证异常
      */
     @ExceptionHandler(BindException.class)
-    public AjaxResult handleBindException(BindException e)
-    {
+    public AjaxResult handleBindException(BindException e) {
         log.error(e.getMessage(), e);
         String message = e.getAllErrors().get(0).getDefaultMessage();
         return AjaxResult.error(message);
@@ -96,8 +91,7 @@ public class GlobalExceptionHandler
      * 自定义验证异常
      */
     @ExceptionHandler(MethodArgumentNotValidException.class)
-    public Object handleMethodArgumentNotValidException(MethodArgumentNotValidException e)
-    {
+    public Object handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
         log.error(e.getMessage(), e);
         String message = e.getBindingResult().getFieldError().getDefaultMessage();
         return AjaxResult.error(message);
@@ -107,8 +101,16 @@ public class GlobalExceptionHandler
      * 演示模式异常
      */
     @ExceptionHandler(DemoModeException.class)
-    public AjaxResult handleDemoModeException(DemoModeException e)
-    {
+    public AjaxResult handleDemoModeException(DemoModeException e) {
         return AjaxResult.error("演示模式,不允许操作");
     }
+
+    /**
+     * 租户用户请求接口携带信息异常
+     */
+    @ExceptionHandler(ClassCastException.class)
+    public AjaxResult handleTenantDateSource(ClassCastException t) {
+        System.err.println("雀巢");
+        return AjaxResult.error("602");
+    }
 }