2011-12-27 2 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

고마워, 구아바 친구들! – Vadzim

+0

그래서 ** ** 유효한 대답으로 표시하십시오.) – Xaerxess