2011-12-27 13 views
18

Sto refactoring del codice per utilizzare guava Cache.Guava cache e conservazione delle eccezioni controllate

codice iniziale:

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

Per non rompere qualcosa che ho bisogno di conservare qualsiasi eccezione generata così com'è, senza avvolgendolo.

soluzione attuale appare un po 'brutta:

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); 
     } 
    } 
} 

C'è un modo possibile per renderlo più bello?

risposta

31

Subito dopo aver scritto la domanda è iniziato a pensare al metodo di utilità alimentato con generici. Quindi ricordato qualcosa su Throwables. E sì, è già lì!)

Potrebbe anche essere necessario gestire UncheckedExecutionException or even ExecutionError.

Quindi la soluzione è:

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); 
    } 
} 

Very nice!

Vedere anche ThrowablesExplained.

+0

Esitato se la domanda con risposta personale deve essere inviata a tutti. Ma questo ha chiarito: http://meta.stackexchange.com/questions/2706/posting-and-answering-questions-you-have-already-found-the-answer-to – Vadzim

+1

E grazie, ragazzi guava! – Vadzim

+0

Quindi contrassegnalo come ** la ** risposta valida;) – Xaerxess

Problemi correlati