Result 와 runCatching

sumi Yoo·2022년 11월 11일
0

Result 와 runCatching

Result와 runCatching은 오류를 처리할 수 있는 방법 중에 하나다. Result는 동작이 성공하든 실패하든 동작의 결과를 캡슐화해서 나중에 처리될 수 있도록 하는 것이 목적이다.

Result

@JvmInline value class Result<out T> /* internal constructor */ {
    val isSuccess: Boolean
    val isFailure: Boolean
    fun getOrNull(): T?
    fun exceptionOrNull(): Throwable?
    
    companion object {
        fun <T> success(value: T): Result<T>
        fun <T> failure(exception: Throwable): Result<T>
    }
}

runCatching

@InlineOnly
@SinceKotlin("1.3")
public inline fun <R> runCatching(block: () -> R): Result<R> {
    return try {
        Result.success(block())
    } catch(e: Throwable) {
        Result.failure(e)
    }
}

Exception을 던지는 함수를 하나 만들었다.

val user = try {
    getUser(userId)
} catch(exception: IllegalStateException) {
    // ... some error handling
    User()
} catch(exception: NullPointerException) {
    // ... some error handling
    User()
}

try-catch를 사용하면 위와 같은 형태이다.

runCatching을 사용하여 Result를 받아서 사용이 가능하다.

val userResult = runCatching {
    getUser(userId)
}

when(result) {
    is Result.Success<LoginResponse> -> {
        // ..
    }
    else -> {
        // error handling
    }
}

Datils about Result

@JvmInline value class Result<out T> /* internal constructor */ {
    val isSuccess: Boolean
    val isFailure: Boolean
    fun getOrNull(): T?
    fun exceptionOrNull(): Throwable?
    
    companion object {
        fun <T> success(value: T): Result<T>
        fun <T> failure(exception: Throwable): Result<T>
    }
}

inline fun <R> runCatching(block: () -> R): Result<R>
inline fun <T, R> T.runCatching(block: T.() -> R): Result<R>

fun <T> Result<T>.getOrThrow(): T
fun <R, T : R> Result<T>.getOrDefault(defaultValue: R): R

inline fun <R, T : R> Result<T>.getOrElse(onFailure: (exception: Throwable) -> R): R
inline fun <R, T> Result<T>.fold(onSuccess: (value: T) -> R, onFailure: (exception: Throwable) -> R): R

inline fun <R, T> Result<T>.map(transform: (value: T) -> R): Result<R>
inline fun <R, T: R> Result<T>.recover(transform: (exception: Throwable) -> R): Result<R>

inline fun <R, T> Result<T>.mapCatching(transform: (value: T) -> R): Result<R>
inline fun <R, T: R> Result<T>.recoverCatching(transform: (exception: Throwable) -> R): Result<R>

inline fun <T> Result<T>.onSuccess(action: (value: T) -> Unit): Result<T>
inline fun <T> Result<T>.onFailure(action: (exception: Throwable) -> Unit): Result<T>

https://dev-repository.tistory.com/105

0개의 댓글

관련 채용 정보