14. sharding-jdbc源碼之異常處理

阿飛Javaer,轉載請註明原創出處,謝謝!

一般項目都會有自己的一套異常處理方式,sharding-jdbc也不以外,sharding-jdbc源碼處理異常的方式主要有下面2種方式:
1. Preconditions
2. 自定義異常

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 <i>element</i> 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的:
1. 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");
        ... ...
    }
    ... ...
}
  1. 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;
}
  1. 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的使用,很明顯能夠讓代碼的逼格提升不少^^;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章