2011-12-27 10 views
18

मैं guava Cache का उपयोग करने के लिए कुछ कोड रीफैक्टर कर रहा हूं।गुवा कैश और चेक अपवादों को संरक्षित करना

प्रारंभिक कोड:

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

संबंधित मुद्दे