2017-05-03 1 views
0

Ich habe den folgenden Codejava komplettierbar Futures und Ausnahme Verkettungs

return future.exceptionally(t -> { 
     if(t instanceof NotFoundException) 
      return processNotFound(responseCb, requestCtx, (NotFoundException) t, errorRoutes, null); 

     throw new CompletionException(t.getMessage(), t); 
     //in scala we would return new CompletableFuture.completeExceptionally(t) and not throw 
    }); 

wo processNotFound eine CompletableFuture gibt auch, dass es versäumt haben könnte.

Grundsätzlich diese Schritte 1. getroffen Primärsystem 2. Fang Ausnahme für Erholung 3. Rückkehr Zukunft der Erholung, die versagt haben oder es gelungen

Ich weiß, wie dies in scala zu tun, aber ich bin nicht sicher, wie man das in Java macht. Weiß jemand?

+0

Warum nicht einfach mit [scala zu Java-Lösung] (http://javatoscala.com/) –

+0

nein danke, zu groß ein Progamm konvertieren @ user7790438 –

+0

https://docs.oracle –

Antwort

2

Nun, kam ich mit meiner eigenen Lösung auf, die einen Hack ist

public static <T> ExceptionOrResult<T> convert(Throwable t, T res) { 
    return new ExceptionOrResult<T>(t, res); 
} 

/** 
* This sucks as I could not find a way to compose failures in java(in scala they have a function for this) 
*/ 
public static <T> CompletableFuture<T> composeFailure(CompletableFuture<T> future, Function<Throwable, CompletableFuture<T>> exceptionally) { 
    return future.handle((r, t) -> convert(t, r)).thenCompose((r) -> { 
     if(r.getException() == null) 
      return CompletableFuture.completedFuture(r.getResult()); 
     return exceptionally.apply(r.getException()); 
    }); 
} 
1

Ja Java 8 hat nicht vielleicht eingebaute, aber es sollte ziemlich einfach sein (ähnlich wie Ihre Antwort oben) hinzuzufügen. Hier ist eine Bibliothek, die es tut: https://github.com/npryce/maybe-java

Aber wenn Sie nur eine CompletableFuture zurückgeben möchten, können Sie versuchen, .thenCompose() Methode verwenden. Hier ein Beispiel:

CompletableFuture<Integer> getCompletableFuture(CompletableFuture<Integer> future) { 
    return future.handle((r, ex) -> { 
     CompletableFuture<Integer> res = new CompletableFuture<>(); 
     if (ex != null) { 
      res.complete(r); 
     } else { 
      res.completeExceptionally(ex); 
     } 
     return res; 
    }).thenCompose(cf -> cf); 
} 
+0

Sorry zu Nitpick, nicht, dass ich Java liebe, aber es hat * Maybe', es heißt einfach 'Optional' – JSelser