點選上方“Java技術驛站”,選擇“置頂公眾號”。
有內涵、有價值的文章第一時間送達!
一般專案都會有自己的一套異常處理方式,sharding-jdbc也不以外,sharding-jdbc原始碼處理異常的方式主要有下麵2種方式:
-
Preconditions
-
自定義異常
1. Preconditions
google-guava的Preconditions用於條件檢查,不符合預期的話則丟擲異常,並可以重寫異常資訊。google-guava原始碼中Preconditions的註釋如下:
Static convenience methods that help a method or constructor check whether it was invoked correctly (whether its preconditions have been met). These methods generally accept a boolean expression which is expected to be true (or in the case of checkNotNull, an object reference which is expected to be non-null). When false (or null) is passed instead, the Preconditions method throws an unchecked exception, which helps the calling method communicate to its caller that that caller has made a mistake.
即幫助我們檢查方法或者建構式是否被正確呼叫,一般接收布林運算式,期望布林運算式的值為true;如果布林運算式的值為false,就會丟擲異常,讓呼叫者知道錯誤的原因。
其部分static方法實現原始碼如下:
-
檢查引數是否正確–expression就是判斷方法的引數的運算式,errorMessage是自定義異常,不允許為空;
// Ensures the truth of an expression involving one or more parameters to the calling method.
public static void checkArgument(boolean expression, @Nullable Object errorMessage) {
if (!expression) {
throw new IllegalArgumentException(String.valueOf(errorMessage));
}
}
-
檢查狀態是否正確–expression就是判斷狀態的引數的運算式,errorMessage是自定義異常,不允許為空;
// Ensures the truth of an expression involving the state of the calling instance, but not involving any parameters to the calling method.
public static void checkState(boolean expression, @Nullable Object errorMessage) {
if (!expression) {
throw new IllegalStateException(String.valueOf(errorMessage));
}
}
-
檢查不允許為空–reference就是待檢查引數,errorMessage是自定義異常,不允許為空;
// Ensures that an object reference passed as a parameter to the calling method is not null.
public static <T> T checkNotNull(T reference, @Nullable Object errorMessage) {
if (reference == null) {
throw new NullPointerException(String.valueOf(errorMessage));
}
return reference;
}
-
檢查下標是否越界–index就是待檢查下標引數,size就是集合的size,errorMessage是自定義異常,不允許為空;
/**
* Ensures that {@code index} specifies a valid element in an array, list or string of size
* {@code size}. An element index may range from zero, inclusive, to {@code size}, exclusive.
*/
public static int checkElementIndex(
int index, int size, @Nullable String desc) {
// Carefully optimized for execution by hotspot (explanatory comment above)
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException(badElementIndex(index, size, desc));
}
return index;
}
接下來我們看一下sharding-jdbc原始碼裡張亮大神是如何使用Preconditions的:
-
Preconditions.checkArgument()的使用 原始碼如下:
@SuppressWarnings("unchecked")
private <T extends ShardingStrategy> T buildShardingAlgorithmClassName(final List<String> shardingColumns, ... ...) {
... ...
// 如果是SingleKeyShardingAlgorithm,那麼sharding column只能有一個
if (shardingAlgorithm instanceof SingleKeyShardingAlgorithm) {
Preconditions.checkArgument(1 == shardingColumns.size(), "Sharding-JDBC: SingleKeyShardingAlgorithm must have only ONE sharding column");
... ...
}
... ...
}
-
Preconditions.checkState()的使用 原始碼如下:
private Collection<String> routeDataSources(final TableRule tableRule) {
... ...
Collection<String> result = strategy.doStaticSharding(tableRule.getActualDatasourceNames(), shardingValues);
// result是路由結果,即原生SQL路由後需要在哪些資料庫中執行,很明顯result肯定不可能為空;
Preconditions.checkState(!result.isEmpty(), "no database route info");
return result;
}
-
Preconditions.checkElementIndex()的使用 原始碼如下(不是來自sharding-jdbc原始碼中,而是筆者寫的):
private static String getFromList(int index){
// 如果從集合中取資料, 首先校驗下標
Preconditions.checkElementIndex(index, list.size(), "index is too big, list size is "+list.size()+". ");
return list.get(index);
}
總結:很明顯,藉助google_guava的Preconditions能夠讓我們的程式碼更優雅,更簡潔;
2. 自定義異常
sharding-jdbc自定義了異常處理類 ShardingJdbcException
:
public class ShardingJdbcException extends RuntimeException {
// 異常類構造方法:異常資訊errorMessage中有多個引數,例如:throw new ShardingJdbcException("Unsupported Date type:%s", convertType);
public ShardingJdbcException(final String errorMessage, final Object... args) {
super(String.format(errorMessage, args));
}
// 把catch的異常轉成ShardingJdbcException型別的異常,並重寫異常資訊
public ShardingJdbcException(final String message, final Exception cause) {
super(message, cause);
}
// 把異常轉成ShardingJdbcException型別的異常,不重寫異常資訊
public ShardingJdbcException(final Exception cause) {
super(cause);
}
}
sharding-jdbc中丟擲自定義日誌場景
-- 丟擲自定義異常並重寫有引數的異常資訊
if (result.isEmpty()) {
throw new ShardingJdbcException("Cannot find table rule and default data source with logic tables: '%s'", logicTables);
}
-
將IllegalAccessException或者InvocationTargetException型別的異常轉化為ShardingJdbcException異常,並重寫異常資訊為"Invoke jdbc method exception"
try {
method.invoke(target, arguments);
} catch (final IllegalAccessException | InvocationTargetException ex) {
throw new ShardingJdbcException("Invoke jdbc method exception", ex);
}
-
把異常轉成ShardingJdbcException型別的異常,不重寫異常資訊
public static void handleException(final Exception exception) {
if (isExceptionThrown()) {
throw new ShardingJdbcException(exception);
}
log.error("exception occur: ", exception);
}
總結
sharding-jdbc對異常的處理還是很有參考價值的,自定義異常型別封裝業務異常,我們一般都會這麼做;但是如果能借鑒sharding-jdbc的原始碼,再增加對 Preconditions
的使用,很明顯能夠讓程式碼的逼格提升不少^^; ```
END