티스토리 뷰

learning

에러(Error, 8/12)

눈침침 2021. 3. 16. 12:55

Tech.io의 'Reactive Programming with Reactor 3'을 공부하면서 정리하는 글입니다.

 

리액터는 에러를 전파하고 복구할 수 있는 여러 연산(=operators)을 가지고 있습니다.
복구는 보통 순서 변경 및 새로운 Subscription구독 과 같은 방법이 있습니다.

문제풀이

에러 발생시 Mono 형태의 기본값을 리턴하는 예

//========================================================================================

// TODO Return a Mono<User> containing User.SAUL when an error occurs in the input Mono, else do not change the input Mono.
Mono<User> betterCallSaulForBogusMono(Mono<User> mono) {
    return mono.onErrorReturn(User.SAUL);
}

에러 발생시 Flux 형태의 기본값을 리턴하는 예

//========================================================================================

// TODO Return a Flux<User> containing User.SAUL and User.JESSE when an error occurs in the input Flux, else do not change the input Flux.
Flux<User> betterCallSaulAndJesseForBogusFlux(Flux<User> flux) {
    return flux.onErrorResume(e -> Flux.just(User.SAUL, User.JESSE));
}

사실 Flux 형태라기보다 새로운 Subscription을 시작하는 형태입니다.


Checked Exception 다루기

  • try ~ catch 로 감싼 뒤, RuntimeException 으로 감싸서 전달(=be signalled downstream.)
  • Exceptions#propagate 유틸 이용: 자동으로 특별한 RuntimeException으로 처리되며, 구독시 자동으로 원래의 예외로 처리됨(=automatically unwrapped), 스택 트레이스에 불필요한 예외가 나타나지 않음(오옹?)
//========================================================================================

// TODO Implement a method that capitalizes each user of the incoming flux using the
// #capitalizeUser method and emits an error containing a GetOutOfHereException error
Flux<User> capitalizeMany(Flux<User> flux) {
    return flux.map(user -> {
    try {
      return capitalizeUser(user);
    } catch (GetOutOfHereException ex) {
      throw Exceptions.propagate(ex);
    }
  });
}

User capitalizeUser(User user) throws GetOutOfHereException {
    if (user.equals(User.SAUL)) {
        throw new GetOutOfHereException();
    }
    return new User(user.getUsername(), user.getFirstname(), user.getLastname());
}

protected final class GetOutOfHereException extends Exception {
    private static final long serialVersionUID = 0L;
}
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함