21 Nisan 2021 Çarşamba

CompletableFuture.exceptionally metodu - Exception Varsa Varsayılan Değer Dönebiliriz

Future vs CompletableFuture
Açıklaması  şöyle. Yani Future ile sadece Exception'a erişebiliyoruz, CompletableFuture daha fazla imkan sunuyor.
Exception Handling: CompletableFuture provides better exception handling than Future. With Future, you can only check if the computation completed successfully or not. If an exception occurs during the computation, you have to catch it explicitly. In contrast, with CompletableFuture, you can handle exceptions in a more declarative way using methods like exceptionally() and handle().
Açıklaması şöyle
Any Exception which occurs within a task ( which is not caught in that task ) will transition a CompletableFuture’s state to CompletedExceptionally.

This exception will then propagate downstream to all dependent tasks if nothing is done to prevent this.

Let’s explore some of the options available to us within the API to deal with such a scenario:

- exceptionally()
- handle()
- whenComplete()
Eğer exceptionally kullanıyorsak açıklaması şöyle
- Allows you to recover from an exception in the pipeline
- You can supply an alternate value, or propagate exception further if you wish to do so:
Açıklaması şöyle
returns a new CompletionStage that upon exceptional completion transforms the exception of this stage and returns the new result
Örnek
Şöyle yaparız
CompletableFuture<Object> getNameF = CompletableFuture.supplyAsync(() -> {
  throw new RuntimeException("foo");
}).exceptionally (t -> "bar");

getNameF.thenAcccept(name -> {
  System.out.println("Name" + name;
});
Örnek
Şöyle yaparız
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
    int result = 10 / 0; // Causes an ArithmeticException
    return result;
});

future.exceptionally(ex -> {
    System.out.println("Exception occurred: " + ex.getMessage());
    return 0; // Default value to return if there's an exception
}).thenAccept(result -> {
    System.out.println("Result: " + result);
});

Hiç yorum yok:

Yorum Gönder