歡迎光臨
每天分享高質量文章

【死磕Sharding-jdbc】—異常處理

點選上方“Java技術驛站”,選擇“置頂公眾號”。

有內涵、有價值的文章第一時間送達!

一般專案都會有自己的一套異常處理方式,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是自定義異常,不允許為空;

  1. // Ensures the truth of an expression involving one or more parameters to the calling method.

  2. public static void checkArgument(boolean expression, @Nullable Object errorMessage) {

  3.    if (!expression) {

  4.        throw new IllegalArgumentException(String.valueOf(errorMessage));

  5.    }

  6. }

  • 檢查狀態是否正確–expression就是判斷狀態的引數的運算式,errorMessage是自定義異常,不允許為空;

  1. // Ensures the truth of an expression involving the state of the calling instance, but not involving any parameters to the calling method.

  2. public static void checkState(boolean expression, @Nullable Object errorMessage) {

  3.    if (!expression) {

  4.        throw new IllegalStateException(String.valueOf(errorMessage));

  5.    }

  6. }

  • 檢查不允許為空–reference就是待檢查引數,errorMessage是自定義異常,不允許為空;

  1. // Ensures that an object reference passed as a parameter to the calling method is not null.

  2. public static <T> T checkNotNull(T reference, @Nullable Object errorMessage) {

  3.    if (reference == null) {

  4.        throw new NullPointerException(String.valueOf(errorMessage));

  5.    }

  6.    return reference;

  7. }

  • 檢查下標是否越界–index就是待檢查下標引數,size就是集合的size,errorMessage是自定義異常,不允許為空;

  1. /**

  2. * Ensures that {@code index} specifies a valid element in an array, list or string of size

  3. * {@code size}. An element index may range from zero, inclusive, to {@code size}, exclusive.

  4. */

  5. public static int checkElementIndex(

  6.        int index, int size, @Nullable String desc) {

  7.    // Carefully optimized for execution by hotspot (explanatory comment above)

  8.    if (index < 0 || index >= size) {

  9.        throw new IndexOutOfBoundsException(badElementIndex(index, size, desc));

  10.    }

  11.    return index;

  12. }

接下來我們看一下sharding-jdbc原始碼裡張亮大神是如何使用Preconditions的:

  1. Preconditions.checkArgument()的使用 原始碼如下:

  1. @SuppressWarnings("unchecked")

  2. private <T extends ShardingStrategy> T buildShardingAlgorithmClassName(final List<String> shardingColumns, ... ...) {

  3.    ... ...

  4.    // 如果是SingleKeyShardingAlgorithm,那麼sharding column只能有一個

  5.    if (shardingAlgorithm instanceof SingleKeyShardingAlgorithm) {

  6.        Preconditions.checkArgument(1 == shardingColumns.size(), "Sharding-JDBC: SingleKeyShardingAlgorithm must have only ONE sharding column");

  7.        ... ...

  8.    }

  9.    ... ...

  10. }

  1. Preconditions.checkState()的使用 原始碼如下:

  1. private Collection<String> routeDataSources(final TableRule tableRule) {

  2.    ... ...

  3.    Collection<String> result = strategy.doStaticSharding(tableRule.getActualDatasourceNames(), shardingValues);

  4.    // result是路由結果,即原生SQL路由後需要在哪些資料庫中執行,很明顯result肯定不可能為空;

  5.    Preconditions.checkState(!result.isEmpty(), "no database route info");

  6.    return result;

  7. }

  1. Preconditions.checkElementIndex()的使用 原始碼如下(不是來自sharding-jdbc原始碼中,而是筆者寫的):

  1. private static String getFromList(int index){

  2.    // 如果從集合中取資料, 首先校驗下標

  3.    Preconditions.checkElementIndex(index, list.size(), "index is too big, list size is "+list.size()+". ");

  4.    return list.get(index);

  5. }

總結:很明顯,藉助google_guava的Preconditions能夠讓我們的程式碼更優雅,更簡潔;

2. 自定義異常

sharding-jdbc自定義了異常處理類 ShardingJdbcException

  1. public class ShardingJdbcException extends RuntimeException {

  2.    // 異常類構造方法:異常資訊errorMessage中有多個引數,例如:throw new ShardingJdbcException("Unsupported Date type:%s", convertType);

  3.    public ShardingJdbcException(final String errorMessage, final Object... args) {

  4.        super(String.format(errorMessage, args));

  5.    }

  6.    // 把catch的異常轉成ShardingJdbcException型別的異常,並重寫異常資訊

  7.    public ShardingJdbcException(final String message, final Exception cause) {

  8.        super(message, cause);

  9.    }

  10.    // 把異常轉成ShardingJdbcException型別的異常,不重寫異常資訊

  11.    public ShardingJdbcException(final Exception cause) {

  12.        super(cause);

  13.    }

  14. }

sharding-jdbc中丟擲自定義日誌場景

-- 丟擲自定義異常並重寫有引數的異常資訊

  1. if (result.isEmpty()) {

  2.    throw new ShardingJdbcException("Cannot find table rule and default data source with logic tables: '%s'", logicTables);

  3. }

  • 將IllegalAccessException或者InvocationTargetException型別的異常轉化為ShardingJdbcException異常,並重寫異常資訊為"Invoke jdbc method exception"

  1. try {

  2.    method.invoke(target, arguments);

  3. } catch (final IllegalAccessException | InvocationTargetException ex) {

  4.    throw new ShardingJdbcException("Invoke jdbc method exception", ex);

  5. }

  • 把異常轉成ShardingJdbcException型別的異常,不重寫異常資訊

  1. public static void handleException(final Exception exception) {

  2.    if (isExceptionThrown()) {

  3.        throw new ShardingJdbcException(exception);

  4.    }

  5.    log.error("exception occur: ", exception);

  6. }

總結

sharding-jdbc對異常的處理還是很有參考價值的,自定義異常型別封裝業務異常,我們一般都會這麼做;但是如果能借鑒sharding-jdbc的原始碼,再增加對 Preconditions的使用,很明顯能夠讓程式碼的逼格提升不少^^; ```

END

贊(0)

分享創造快樂

© 2024 知識星球   網站地圖