spring boot 全局异常处理可以通过配置 @controlleradvice 捕获 shardingsphere 抛出的 shardingsphereexception 来拦截路由异常。具体做法是在全局异常处理器中检查异常类型,若为 shardingsphereexception 则提取其根本原因(如 tablenotfoundexception),并返回统一的错误响应。这样做可以确保所有与分片路由相关的错误都被集中处理,避免将原始堆栈信息暴露给前端。

如何区分具体的路由失败原因
在捕获到 ShardingSphereException 后,需要进一步判断是表不存在、数据源不可用还是 SQL 语法错误。通过遍历异常的 cause 链,可以定位到具体的 SQLException 或 ShardingSphere 内部异常类。例如,当分片键缺失导致无法路由时,通常会抛出 MissingShardingColumnException。识别这些具体原因有助于提供更精准的错误提示,比如提示用户补充必填的分片字段。

import org.apache.shardingsphere.exception.ShardingSphereException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ShardingSphereException.class)
public String handleShardingException(ShardingSphereException e) {
Throwable cause = e.getCause();
if (cause instanceof java.sql.SQLException) {
return "Database routing error: " + cause.getMessage();
}
return "Sharding routing failed: " + e.getMessage();
}
}
如何处理多数据源路由失败的情况
当 ShardingSphere 尝试路由到多个数据源但部分数据源不可用时,会触发路由异常。此时应检查异常中是否包含 CannotGetJdbcConnectionException 或其他连接相关异常。针对这种情况,可以在全局处理器中记录日志并返回服务降级响应,而不是直接抛出 500 错误。这样可以提高系统的可用性,允许部分功能在非核心数据源故障时继续运行。

import org.springframework.jdbc.CannotGetJdbcConnectionException;
import org.apache.shardingsphere.exception.ShardingSphereException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ShardingSphereException.class)
public String handleMultiDataSourceError(ShardingSphereException e) {
Throwable cause = e;
while (cause != null) {
if (cause instanceof CannotGetJdbcConnectionException) {
return "Data source unavailable, please try again later.";
}
cause = cause.getCause();
}
return "Unknown sharding error occurred.";
}
}
基于分片键缺失导致的特定异常处理
当请求中缺少必要的分片键时,ShardingSphere 会在路由阶段抛出 MissingShardingColumnException。这是路由异常中最常见的一种情况。在全局异常处理器中,可以专门针对这一异常类型进行捕获,并返回明确的提示信息,告知客户端必须提供分片键才能执行查询。这种处理方式比通用的 ShardingSphereException 捕获更精确,有助于快速定位问题。



















