CoroutineUtils

코루틴 유틸리티. 안전한 코루틴 실행 지원.

예외 핸들러

CustomCoroutineExceptionHandler

class CustomCoroutineExceptionHandler :
    AbstractCoroutineContextElement(CoroutineExceptionHandler),
    CoroutineExceptionHandler

코루틴 예외 처리. RestExceptionHandler를 통해 로깅 및 Sentry 전송.

실행 함수

withBlocking()

fun <T> withBlocking(
    context: CoroutineContext = EmptyCoroutineContext,
    block: suspend CoroutineScope.() -> T
) = runBlocking(context + SupervisorJob() + CustomCoroutineExceptionHandler() + MDCContext())

블로킹 코루틴 실행. MDC 컨텍스트 유지.

withLaunch()

fun CoroutineScope.withLaunch(
    context: CoroutineContext = EmptyCoroutineContext,
    start: CoroutineStart = CoroutineStart.DEFAULT,
    block: suspend CoroutineScope.() -> Unit
): Job

비블로킹 코루틴 실행 (fire-and-forget).

withAsync()

fun <T> CoroutineScope.withAsync(
    context: CoroutineContext = EmptyCoroutineContext,
    start: CoroutineStart = CoroutineStart.DEFAULT,
    block: suspend CoroutineScope.() -> T
): Deferred<T>

비블로킹 코루틴 실행 (결과 반환).

병렬 매핑 함수

pmap()

suspend fun <T, R> Iterable<T>.pmap(
    block: suspend CoroutineScope.(T) -> R,
): Pair<List<R>, List<Throwable>>

병렬 매핑. 성공 결과와 예외를 분리하여 반환.

pmapIndexed()

suspend fun <T, R> Iterable<T>.pmapIndexed(
    block: suspend CoroutineScope.(index: Int, T) -> R,
): Pair<List<R>, List<Throwable>>

인덱스 포함 병렬 매핑.

결과 처리 함수

onFailure()

suspend fun <T> Pair<List<T>, List<Throwable>>.onFailure(
    action: suspend CoroutineScope.(exceptions: List<Throwable>, successes: List<T>) -> Unit
): Pair<List<T>, List<Throwable>>

실패 시 추가 액션 실행.

getOrEmpty()

fun <T> Pair<List<T>, List<Throwable>>.getOrEmpty(): List<T>

성공 결과만 반환 (예외 무시).

getOrThrow()

fun <T> Pair<List<T>, List<Throwable>>.getOrThrow(): List<T>

예외 있으면 첫 번째 예외 throw.

코루틴 컨텍스트

SupervisorJob()        // 자식 실패가 부모에 영향 안 줌
+ CustomCoroutineExceptionHandler()  // 예외 처리
+ MDCContext()         // MDC 전파

특징

  • SupervisorJob: 부분 실패 허용
  • MDC 전파: slf4j-mdc-coroutines 사용
  • 예외 분리: 성공/실패 결과 분리 반환
  • Sentry 연동: 예외 자동 보고