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;
}