2011-12-27 6 views
18

guava Cacheを使用するコードをリファクタリングしています。Guavaのキャッシュとチェックされた例外の保護

初期コード:

public Post getPost(Integer key) throws SQLException, IOException { 
    return PostsDB.findPostByID(key); 
} 

私があるとして、それをラップすることなく、任意のスローされた例外を維持するために必要な何かを破るしないために。

現在のソリューションは、やや醜い表示されます:

public Post getPost(final Integer key) throws SQLException, IOException { 
    try { 
     return cache.get(key, new Callable<Post>() { 
      @Override 
      public Post call() throws Exception { 
       return PostsDB.findPostByID(key); 
      } 
     }); 
    } catch (ExecutionException e) { 
     Throwable cause = e.getCause(); 
     if (cause instanceof SQLException) { 
      throw (SQLException) cause; 
     } else if (cause instanceof IOException) { 
      throw (IOException) cause; 
     } else if (cause instanceof RuntimeException) { 
      throw (RuntimeException) cause; 
     } else if (cause instanceof Error) { 
      throw (Error) cause; 
     } else { 
      throw new IllegalStateException(e); 
     } 
    } 
} 

は、それがよりよいようにするすべての可能な方法はありますか?

答えて

31

質問を書いた直後に、ジェネリックで動くユーティリティメソッドについて考え始めました。 その後、約Throwablesと記憶されています。 はい、既にそこにあります! )

UncheckedExecutionException or even ExecutionErrorも処理する必要があります。

だから、解決策は以下のとおりです。

public Post getPost(final Integer key) throws SQLException, IOException { 
    try { 
     return cache.get(key, new Callable<Post>() { 
      @Override 
      public Post call() throws Exception { 
       return PostsDB.findPostByID(key); 
      } 
     }); 
    } catch (ExecutionException e) { 
     Throwables.propagateIfPossible(
      e.getCause(), SQLException.class, IOException.class); 
     throw new IllegalStateException(e); 
    } catch (UncheckedExecutionException e) { 
     Throwables.throwIfUnchecked(e.getCause()); 
     throw new IllegalStateException(e); 
    } 
} 

非常に素晴らしいです!

ThrowablesExplainedも参照してください。

+0

自己回答の質問を投稿する必要がある場合は躊躇します。しかし、これは明らかにした:http://meta.stackexchange.com/questions/2706/posting-and-answering-questions-you-have-already-found-the-answer-to – Vadzim

+1

そして、ありがとう、guavaみんな! – Vadzim

+0

** **有効回答;)と書いてください – Xaerxess

関連する問題