Pular para o conteúdo
Snippets·Grátis

runCatching → Result<T, AppError>

Tiny extension that lifts thrown exceptions into a typed Result<T, AppError>, so callers can pattern-match instead of try/catch.

Instalação grátis.

Se o PocketCode estiver instalado no seu Android, isto abre a página no app.

Prévia

Result.kt · 71 linhas
/**
 * Tiny error-handling helpers. Turns thrown exceptions into a typed
 * Result<T, AppError> so callers can branch on the failure shape
 * rather than wrap every call in try/catch.
 *
 * Usage:
 *
 *     val user: Result<User, AppError> = catching {
 *         repo.fetchUser(id)
 *     } onError {
 *         when (it) {
 *             is IOException        -> AppError.Network(it)
 *             is HttpException      -> AppError.Server(it.code(), it.message())
 *             else                  -> AppError.Unknown(it)
 *         }
 *     }
 *     when (user) {
 *         is Result.Ok    -> render(user.value)
 *         is Result.Fail  -> showError(user.error)
 *     }
 */

sealed interface Result<out T, out E> {
    data class Ok<T>(val value: T) : Result<T, Nothing>
    data class Fail<E>(val error: E) : Result<Nothing, E>
}

inline fun <T> catching(block: () -> T): T? =
    try {
        block()
    } catch (t: Throwable) {
        null
    }

inline infix fun <T, E> (T?).onError(map: (Throwable) -> E): Result<T, E> = TODO(
    """
    This helper has two flavours; pick the one that matches your call site:

    1. If you already caught the exception with `catching { … }` you have a
       T?. Combine with this and an explicit Throwable would need to be
       smuggled — not possible without a real `try`. Use form (2) below.

    2. Use `catchingWith` for the typed variant:

           inline fun <T, E> catchingWith(
               errorMap: (Throwable) -> E,
               block: () -> T,
           ): Result<T, E> = try {
               Result.Ok(block())
           } catch (t: Throwable) {
               Result.Fail(errorMap(t))
           }
    """,
)

/** Use this in real code. */
inline fun <T, E> catchingWith(
    errorMap: (Throwable) -> E,
    block: () -> T,
): Result<T, E> = try {
    Result.Ok(block())
} catch (t: Throwable) {
    Result.Fail(errorMap(t))
}

/** Common AppError sealed type users can copy and adapt. */
sealed interface AppError {
    data class Network(val cause: Throwable) : AppError
    data class Server(val code: Int, val body: String?) : AppError
    data class Unknown(val cause: Throwable) : AppError
}

Mudanças na 1.0.0

Initial release.

Relacionados