В статье о том как к этому подготовиться, ну а я предлагаю взглянуть на side-by-side пример:
Было
fun loadConfig(path: Path): Result<Config> =
runCatching { fileSystem.readBytes(path) }
.mapCatching { bytes -> parseConfig(bytes) }
.recover { e ->
if (e is NoSuchFileException) defaultConfig() else throw e
}
fun useConfig(path: Path) {
loadConfig(path)
.onSuccess { cfg -> startApp(cfg) }
.onFailure { e ->
when (e) {
is NoSuchFileException -> showMissingConfigWarning()
is ConfigFormatException -> showConfigParseError(e)
else -> showGenericError(e)
}
}
}
Стало
// Rich errors
// Define error variants (could be data objects/classes in your domain)
data object IoFailure
data class ParseFailure(val details: String)
fun loadConfig(path: Path): Config | IoFailure | ParseFailure
fun useConfigRich(path: Path) {
when (val r = loadConfig(path)) {
is Config -> startApp(r)
is IoFailure -> showMissingConfigWarning()
is ParseFailure -> showConfigParseErrorMessage(r.details)
}
}