2011-12-27 21 views
18

guava Cache'u kullanmak için bazı kodları yeniden yapıyorum.Guava önbelleğini ve denetlenen istisnaları koruma

Başlangıç ​​kodu: sarma olmadan ben olduğu gibi herhangi bir istisnayı korumak için gereken şey, kırmamaya amacıyla

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

.

Güncel çözüm biraz çirkin görünür: bu güzel yapar için olası bir yol

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

var mı?

cevap

31

Sadece yazdıktan sonra soru jenerik ile güçlendirilmiş yardımcı programı düşünmeye başladı. Ardından, Throwables ile ilgili bir şey hatırladı. Ve evet, o zaten var!) UncheckedExecutionException or even ExecutionError işlemek de gerekebilir.

Yani çözümdür:

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

Çok güzel! Ayrıca bkz. ThrowablesExplained. Kendiliğinden cevaplanan soru hiç gönderilmemeli, durdurulamıyor.

+0

. Ama bu açıklığa kavuşturdu: http://meta.stackexchange.com/questions/2706/posting-and-answering-questions-you-have-already-found-the-answer-to – Vadzim

+1

Ve teşekkür ederim, guava çocuklar! – Vadzim

+0

Yani ** ** geçerli cevap olarak işaretleyin;) – Xaerxess