[Spring][WebFlux] Error 처리 & Retry

Sun Ji·2023년 2월 20일
0

삽질로그

목록 보기
1/4

topic: Spring Webflux에서 Mono/Flux를 처리할 때 Exception 등의 에러를 처리하는 방법
(onError 시그널의 처리)

Error

1. onErrorReturn

  • Error가 발생했을 경우 정적 기본값 또는 exception을 반환
  • 발생한 exception이 특정 조건을 충족하는 경우에만 사용할 수도 있다

예시)

/* 
* error를 발생시키는 함수 errorFunc
* return type : Mono<Int>
*/
errorFunc()
    .onErrorReturn(0)

2. onErrorResume

  • Error가 발생했을 경우 다른 시퀀스나 에러로 대체
  • error를 입력으로 받아 publisher를 리턴

예시)

errorFunc()
    .onErrorResume { throwable ->
        // Do on error
        Mono.just(0)
    }
    
/*
* 특정 Exception만 처리 가능
*/
errorFunc()
    .onErrorResume(SomeException::class.java) {
        // DO SOMETHING
        Mono.just(0)
    }

3. onErrorContinue

  • Error가 발생했을 때 skip해서 동작

4. onErrorMap

  • Exception을 캐치하고 다른 exception으로 대체

예시)

errorFunc()
	.onErrorMap { throwable ->
    	OtherException("Transfoem any error")
    }

Retry

1. retry

  • Error가 발생한 원본 시퀀스를 재구독한다.
  • retry(long numRetries = Long.MAX_VALUE) : retry 횟수가 없다면 Long.MAX_VALUE 값을 이용한다

예시)

/*
* 실패시 3번 재시도
*/
errorFunc()
	.retry(3)

2. retryWhen

public final Flux<T> retryWhen(Retry retrySpec) {
	return onAssembly(new FluxRetryWhen<>(this, retrySpec));
}

예시)

errorFunc()
	.retryWhen(
    	Retry.max(2)
    )
    
errorFunc()
	.retryWhen(
    	Retry.backoff(2, Duration.ofSeconds(5)) // 5초 간격, 2번 retry
    )
    
/*
* 특정 exception 처리
*/
errorFunc()
	.retryWhen(
    	Retry.max(2)
        	.filter(Predicate.isEqual(SomeException::class.java))
            .doAfterRetry {
            	// Do something after retry
            }
    )
    

+) 참고
public abstract class Retry

: Base abstract class for a strategy to decide when to retry given a companion Flux of Retry.RetrySignal, for use with Flux.retryWhen(Retry) and reactor.core.publisher.Mono.retryWhen(Retry). Also provides access to configurable built-in strategies via static factory methods:

  • indefinitely()
  • max(long)
  • maxInARow(long)
  • fixedDelay(long, Duration)
  • backoff(long, Duration)

Users are encouraged to provide either concrete custom Retry strategies or builders that produce such concrete Retry. The RetrySpec returned by e.g. max(long) is a good inspiration for a fluent approach that generates a Retry at each step and uses immutability/copy-on-write to enable sharing of intermediate steps (that can thus be considered templates).

profile
매일매일 삽질중...

0개의 댓글