代码片段·免费
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.