Saltar al contenido
Snippets·Gratis

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.

Se instala gratis.

Si tienes PocketCode instalado en tu Android, esto abre la página en la app.

Vista previa

Result.kt · 71 líneas
/**
 * 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
}

Cambios en la 1.0.0

Initial release.

Relacionados

Snippets de Kotlin y AndroidGratisSnippets20 snippets de Kotlin para apps Android: estado de UI sellado, un ViewModel de Hilt con StateFlow, corrutinas, entidades y DAO de Room, y estado y listas de Compose. Escribe un prefijo como uistate o hiltvm en un archivo .kt.Snippets de RustGratisSnippets20 snippets de Rust que solo usan la biblioteca estándar, salvo un struct con serde: enums de error con From, cadenas de iteradores, contar con HashMap, let else, hilos con Arc y Mutex, canales y un módulo de tests.Hook useDebounce (React)GratisSnippetsuseDebounce y useDebouncedCallback en TypeScript, más un ejemplo de caja de búsqueda. Los dos cancelan su temporizador cuando el componente se desmonta.Snippets de HTML y CSSGratisSnippets8 snippets de HTML (zonas de la página, etiquetas Open Graph, picture, dialog, una tabla con cabeceras) y 12 de CSS (reset, diseños con grid, clamp, variables para el modo oscuro, movimiento reducido, container queries).Snippets de BashGratisSnippets20 snippets de Bash para scripts: cabecera segura, comprobación de argumentos, getopts, bucles sobre archivos y arrays, limpieza con trap, reintentos y unos cuantos comandos de git. Escribe el prefijo en un archivo .sh.Snippets de JavaScript y TypeScriptGratisSnippets12 snippets de JavaScript (fetch con tiempo límite, Promise.allSettled, agrupar, localStorage) y 8 de TypeScript (guardas de tipo, switch exhaustivo, as const, satisfies). Los de JavaScript salen en archivos .js y los de TypeScript en archivos .ts.