跳转到内容
代码片段·免费

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.

免费安装。

如果你的 Android 设备上装了 PocketCode,这会在应用里打开此页面。

预览

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

1.0.0 的变更

Initial release.

相关

Kotlin 与 Android 代码片段免费代码片段20 个面向 Android 应用的 Kotlin 代码片段:密封 UI 状态、带 StateFlow 的 Hilt ViewModel、协程、Room 实体与 DAO,以及 Compose 状态和列表。在 .kt 文件中输入 uistate 或 hiltvm 等前缀即可。Rust 代码片段免费代码片段20 个 Rust 代码片段,除一个 serde 结构体外只用标准库:带 From 的错误枚举、迭代器链、用 HashMap 计数、let else、配合 Arc 和 Mutex 的线程、通道以及测试模块。useDebounce 钩子(React)免费代码片段TypeScript 版的 useDebounce 和 useDebouncedCallback,附一个搜索框示例。组件卸载时两者都会清除计时器。HTML 与 CSS 代码片段免费代码片段8 个 HTML 代码片段(页面地标、Open Graph 标签、picture、dialog、带表头的表格)和 12 个 CSS 代码片段(重置样式、grid 布局、clamp、深色模式变量、减少动效、容器查询)。Bash 代码片段免费代码片段20 个用于脚本的 Bash 代码片段:安全的脚本开头、参数检查、getopts、遍历文件和数组、用 trap 清理、重试以及几个 git 命令。在 .sh 文件中输入前缀即可。JavaScript 与 TypeScript 代码片段免费代码片段12 个 JavaScript 代码片段(带超时的 fetch、Promise.allSettled、分组、localStorage)和 8 个 TypeScript 代码片段(类型守卫、穷尽 switch、as const、satisfies)。JavaScript 片段出现在 .js 文件中,TypeScript 片段出现在 .ts 文件中。