2017-07-07 54 views
0

我期待創造一個例外工廠Java異常工廠較高水平異常

我有一個連接到不同的數據存儲和這些數據存儲拋出一些例外的服務。 我不想將這些例外返回給服務的用戶,而是返回更高級別的例外 storeServiceTransientReadException

當連接到數據存儲時,我將使用try,catch拋出模式;例如,對於卡桑德拉連接:

public ResultSet safeExecute(Statement statement) throws StoreServiceException { 
    try { 
     return session.execute(statement); 
    } 
    catch(QueryExecutionException ex){ 
     log.error(ex); 
     StoreServiceException storeException = StoreServiceExceptionFactory.getTransientException(ex); 
     throw storeException; 
    } 

在卡桑德拉的例子,我想該工廠創建一個讀或寫這取決於是否異常是ReadFailureException,ReadTimeoutException,WriteFailureException或WriteTimeoutException

對於其他數據storeServiceException例外商店我想要遵循相同的模式,那麼服務的用戶只需要擔心服務錯誤而不是特定的數據存儲錯誤。

對於工廠我想沿(僞)線的東西:

public class ExceptionsFactory { 

public StoreServiceTransientException getTransientException(Exception ex){ 

    if ReadException 
     return StoreServiceTransientException("read exception ") 


    if WriteException 
     return StoreServiceTransientException("write exception ") 

} 

public StoreServiceNonTransientException getTransientNonException(Exception ex){ 

    if ReadException 
     return StoreServiceNonTransientException("read exception ") 


    if WriteException 
     return StoreServiceNonTransientException("write exception ") 


} 

但我無法找到這裏面我擔心許多網上的例子。 這是一個非常糟糕的主意? 我應該只有更多特定的catch塊返回我想要的storeServiceException?

+2

在Java中,通常的做法是類名以大寫字母開頭。 'StoreServiceTransientException'將是一個快速但巨大的改進 – byxor

+0

@byxor好點 - 當我嘗試使示例更通用 – JJHolloway

回答

1

這是一個非常糟糕的主意?在我看來,是的。這是一個壞主意。使用Exception(s)的昂貴部分正在填充堆棧跟蹤。如果您預先創建並保存了您所拋出的Exception,那麼堆棧跟蹤將變得毫無意義(或至少大大降低了值)。您還沒有登錄當前堆棧跟蹤,所以我也會改變

log.error(ex); 

log.error("Caught exception: " + ex.getMessage(), ex); 

而且具有相似的根本原因實例化的例外 -

throw new storeServiceException("Exception in storage.", ex); 

而且名稱應遵循正常的命名約定。 Java類名稱以大寫字母開頭 - 「你」看起來像一個變量。

+0

我不好 - 更新示例並刪除了錯字時,我的部分錯別字。謝謝(你的)信息! – JJHolloway