2011-12-27 10 views
18

Estoy refaccionando algunos códigos para usar guava Cache.caché de guayaba y conservar excepciones marcadas

código inicial:

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

Con el fin de no romper algo que necesito para preservar cualquier excepción lanzada como es, sin envolverlo.

solución actual parece algo feo:

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

¿Hay alguna forma posible para que sea más agradable?

Respuesta

31

Justo después de escribir, la pregunta comenzó a pensar en el método de utilidad con genéricos. Luego recordó algo sobre Throwables. ¡Y sí, ya está allí!)

También puede ser necesario manejar UncheckedExecutionException or even ExecutionError.

Así que la solución es:

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

muy agradable!

Véase también ThrowablesExplained.

+0

Vacila si la pregunta autocompuesta debe publicarse en absoluto. Pero esto dejó en claro: http://meta.stackexchange.com/questions/2706/posting-and-answering-questions-you-have-already-found-the-answer-to – Vadzim

+1

Y gracias, guava chicos! – Vadzim

+0

Así que márquelo como ** la ** respuesta válida;) – Xaerxess

Cuestiones relacionadas