update 优化 删除Threads类 已经不需要了

This commit is contained in:
疯狂的狮子Li
2025-09-26 15:24:04 +08:00
parent 5c634940c2
commit 2fe4c96706
3 changed files with 83 additions and 110 deletions

View File

@@ -6,7 +6,6 @@ import com.baomidou.dynamic.datasource.exception.CannotFindDataSourceException;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.utils.Threads;
import org.mybatis.spring.MyBatisSystemException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
@@ -37,7 +36,7 @@ public class MybatisExceptionHandler {
@ExceptionHandler(MyBatisSystemException.class)
public R<Void> handleCannotFindDataSourceException(MyBatisSystemException e, HttpServletRequest request) {
String requestURI = request.getRequestURI();
Throwable root = Threads.getRootCause(e);
Throwable root = getRootCause(e);
if (root instanceof NotLoginException) {
log.error("请求地址'{}',认证失败'{}',无法访问系统资源", requestURI, root.getMessage());
return R.fail(HttpStatus.HTTP_UNAUTHORIZED, "认证失败,无法访问系统资源");
@@ -50,4 +49,41 @@ public class MybatisExceptionHandler {
return R.fail(HttpStatus.HTTP_INTERNAL_ERROR, e.getMessage());
}
/**
* 获取异常的根因(递归查找)
*
* @param e 当前异常
* @return 根因异常(最底层的 cause
* <p>
* 逻辑说明:
* 1. 如果 e 没有 cause说明 e 本身就是根因,直接返回
* 2. 如果 e 的 cause 和自身相同(防止循环引用),也返回 e
* 3. 否则递归调用,继续向下寻找最底层的 cause
*/
public static Throwable getRootCause(Throwable e) {
Throwable cause = e.getCause();
if (cause == null || cause == e) {
return e;
}
return getRootCause(cause);
}
/**
* 在异常链中查找指定类型的异常
*
* @param e 当前异常
* @param clazz 目标异常类
* @return 找到的指定类型异常,如果没有找到返回 null
*/
public static Throwable findCause(Throwable e, Class<? extends Throwable> clazz) {
Throwable t = e;
while (t != null && t != t.getCause()) {
if (clazz.isInstance(t)) {
return t;
}
t = t.getCause();
}
return null;
}
}