exceptionally

exceptionally: block that runs when an exception occurs

  future
    .exceptionally { ex: Throwable? -> fallbackMaker(ex) }
    .thenAccept { x: String -> out.println(x) }
GT-Snapshot

Code

package com.glassthought.sandbox

import gt.sandbox.util.output.Out
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import java.util.concurrent.CompletableFuture

val out = Out.standard()

fun main() = runBlocking {
  val future = CompletableFuture.supplyAsync {
    throw RuntimeException("original-exc-msg-from-supplyAsync-future-block")
    out.println("supplyAsync")
    "Jon Snow"
  }

  future
    .exceptionally { ex: Throwable? -> fallbackMaker(ex) }
    .thenAccept { x: String -> out.println(x) }

  delay(100)
  println()
}

private fun fallbackMaker(ex: Throwable?): String {
  return "Fallback Result (${ex?.message})"
}

Command to reproduce:

gt.sandbox.checkout.commit db510bcf58d24150f27d \
&& cd "${GT_SANDBOX_REPO}" \
&& cmd.run.announce "./gradlew run"

Recorded output of command:

> Task :app:checkKotlinGradlePluginConfigurationErrors SKIPPED
> Task :app:compileKotlin UP-TO-DATE
> Task :app:compileJava NO-SOURCE
> Task :app:processResources NO-SOURCE
> Task :app:classes UP-TO-DATE

> Task :app:run
[2024-11-22T05:23:27.988318Z][elapsed-since-start:   42ms][tname:main/tid:1] Fallback Result (java.lang.RuntimeException: original-exc-msg-from-supplyAsync-future-block)


BUILD SUCCESSFUL in 675ms
2 actionable tasks: 1 executed, 1 up-to-date

Backlinks