본문으로 건너뛰기
Folly Code Review · 71/89

folly::Try vs Expected 선택 기준

· Hawk · 3분 읽기

한 줄 요약: Try<T>비동기 결과 슬롯에 어떤 예외든 받는다. Expected<T, E>도메인 오류를 type-safe enum/struct로 표현한다. 둘은 겹쳐 보이지만 사용 자리가 다르다.

#두 타입의 의도 차이

항목TryExpected<T, E>
오류 타입exception_wrapper (임의 예외)E (보통 enum/struct)
주 사용처Future/Task 결과 슬롯함수 반환값
throw 비용예외 객체 만들 때없음 (그냥 enum)
type-safe 분기runtime type checkcompile-time enum match
monadicthenTry / Future APIthen / transform / orElse
empty 상태있음있음

TryFuture<T>::getTry()의 반환 타입이다. 비동기 결과 슬롯 — 결과가 무엇이든 들어가야 한다. 호출 그래프 중간에서 throw된 임의 예외도 들고 다닌다.

Expected는 함수 시그니처의 반환 타입이다. 이 함수가 어떤 오류를 만들 수 있는지 compile-time에 명시. enum이면 switch가 exhaustive해진다.

#사용 자리 매트릭스

| 도메인 오류 명시 | 임의 예외 캐리어
─────────────|──────────────────|──────────────────
함수 반환 | Expected | Try (드물게 OK)
Future 결과 | Future<E>가 | Try (항상)
| 드물게 가능 |
Variant 슬롯 | variant | Try

핵심 규칙 둘.

  1. 함수 시그니처에서 오류 가능성을 명시하려면Expected.
  2. 비동기 결과를 어떤 형태든 받아 호출자에 전달하려면Try.

#실전 예 — 둘이 만나는 곳

// 도메인 함수 — Expected
folly::Expected<int, ParseError> ParseInt(folly::StringPiece s);
// 비동기 wrapping — Future<int>로 노출
folly::SemiFuture<int> ParseIntAsync(std::string s);
// Future가 throw할 때 호출자가 Try로 받음
folly::SemiFuture<int> f = ParseIntAsync("42");
auto t = std::move(f).getTry(); // Try<int>
if (t.hasValue()) use(*t);
else {
// 어떤 예외든 가능 — ParseError가 throw됐을 수도, network 예외일 수도
if (t.exception().is_compatible_with<ParseException>()) { ... }
else if (t.exception().is_compatible_with<std::system_error>()) { ... }
}

도메인 함수는 Expectedtype-safe enum을 반환하고, 비동기 wrap이 그 함수를 Future로 노출한다. Future 호출자는 Try임의 예외를 받는다. 두 타입이 한 파이프라인에 공존한다.

#변환 패턴

#Expected → Future

folly::SemiFuture<int> ToFuture(folly::Expected<int, ParseError> e) {
if (e) return folly::makeSemiFuture<int>(*e);
return folly::makeSemiFuture<int>(
folly::make_exception_wrapper<ParseException>(e.error()));
}

도메인 오류 enum이 throw하는 예외 타입으로 변환된다. async 경계에서 예외가 정상 메커니즘.

#Future → Expected

folly::Expected<int, ParseError> FromTry(folly::Try<int>&& t) {
if (t.hasValue()) return *t;
if (t.exception().is_compatible_with<ParseException>()) {
return folly::makeUnexpected(
t.exception().get_exception<ParseException>()->error());
}
// 임의 예외 — 도메인 enum으로 표현 불가
return folly::makeUnexpected(ParseError::Unknown);
}

Try → Expected손실이 있다. 임의 예외 → 닫힌 enum이라 정보가 줄어든다. 정말 도메인 안 예외만 다룬다면 OK.

#코드 리뷰 — 무엇이 잘못된 모양인가

// 1. 도메인 함수가 Try 반환
folly::Try<int> ParseInt(folly::StringPiece s);
// → Expected<int, ParseError>. Try는 비동기 슬롯이지 도메인 시그니처가 아님
// 2. Future가 Expected를 노출
folly::Future<folly::Expected<int, ParseError>> compute();
// → 이중 분기. Future가 Expected를 들고 다닐 이유 없음.
// compute()가 throw하거나 Future<int>로 충분.
// 3. Try를 함수 인자로
void process(folly::Try<int> t);
// → 의미가 어색. 호출자가 분기해서 정상값/오류 path로 가는 게 자연스러움.
// 4. Expected의 E가 std::exception_ptr
folly::Expected<int, std::exception_ptr> Compute();
// → Try가 적합. Expected는 도메인 enum/struct를 위함.

#성능 비교

시나리오TryExpected
정상 path (no error)동일 (T 보관)동일 (T 보관)
오류 path (객체 생성)exception_wrapper 비용E 객체 생성 (보통 enum — 무료)
throw 비용예외 생성 시 1회0
catch 비용runtime type checkswitch (분기 1개)
memorysizeof T + ewsizeof T + sizeof E + tag

Expected가 오류 path에서 더 가볍다. enum이면 거의 무료. throw cost가 hot path에 있으면 Expected로 변환해 비용을 줄일 수 있다.

#비동기 코드에서의 일반 가이드

// 도메인 함수 (sync)
Expected<User, AuthError> Authenticate(Token t);
// 비동기 wrapping
SemiFuture<User> AuthenticateAsync(Token t);
// 내부: Authenticate() → Expected → throw → Future
// 호출자
SemiFuture<User> f = AuthenticateAsync(token);
auto t = std::move(f).getTry(); // Try<User>
if (t.hasException<AuthException>()) { ... }

규칙:

  • 시그니처는 Expected (가능한 오류를 닫힌 집합으로 명시).
  • async 경계에서 Future<T>로 노출 — 예외로 오류 전파.
  • async 호출자는 Try<T> 또는 thenTry로 받음.

#한 줄로

Try는 결과 슬롯, Expected는 시그니처.

#자주 보는 안티패턴

// 1. Try와 Expected를 같은 함수에서 혼용
folly::Try<folly::Expected<int, Error>> compute();
// → 의미 없는 이중 wrapping
// 2. Future<Expected<T, E>>
// → Future가 throw하거나 Future<T>면 됨
// 3. 도메인 코드 전체를 Try로
folly::Try<int> Step1();
folly::Try<int> Step2();
// → Expected가 의도를 더 명확히
// 4. Expected의 E에 string
folly::Expected<int, std::string> Foo();
// → enum/struct로 type-safe하게. string은 메시지지 타입이 아님.

#정리

  • Try<T>어떤 결과도 들고 다니는 비동기 슬롯.
  • Expected<T, E>닫힌 오류 집합을 시그니처에 명시.
  • 함수 시그니처는 보통 Expected, async 결과 슬롯은 항상 Try.
  • 두 타입은 한 파이프라인에 공존한다 — async 경계에서 서로 변환.
  • 오류 path 성능이 중요하면 throw 없는 Expected가 유리.

#다음 편

Part 17로 넘어가 Range, Uri, Hash 유틸리티들을 본다.

#관련 항목

Folly Code Review · 72 of 89

  1. 1 Folly Code Review — Meta의 production-grade C++ 라이브러리 코드 분석
  2. 2 Folly 개요 — Meta가 production에서 검증한 utility 모음 분석
  3. 3 Folly vs Abseil 철학 비교 — performance-first vs std-compatible
  4. 4 Folly 빌드와 fbcode 환경 — monorepo의 그림자
  5. 5 Folly API stability 정책 — 어떤 보장도 없다는 솔직함
  6. 6 Folly production validation 문화 — peta-scale에서 단련된 코드
  7. 7 folly::Future 분석 — std::future의 한계를 넘는 composable async
  8. 8 folly::Promise·makeFuture — Future를 만드는 두 길
  9. 9 folly::SemiFuture vs Future — executor binding의 명시화
  10. 10 folly::Future thenValue·thenError·thenTry — continuation 체인 분석
  11. 11 folly::collect·collectAll·collectAny — fan-in 패턴 분석
  12. 12 folly::Future retry·window·via — 제어 흐름 조합자
  13. 13 folly::fibers 분석 — M:N stackful coroutine
  14. 14 folly::InlineExecutor — 호출자 thread에서 즉시 실행
  15. 15 folly::CPUThreadPoolExecutor — CPU-bound 작업의 표준 thread pool
  16. 16 folly::IOThreadPoolExecutor — libevent 기반 I/O pool
  17. 17 folly::ManualExecutor — 결정적 테스트를 위한 수동 진행
  18. 18 folly::EventBase 분석 — libevent 이벤트 루프의 핵심
  19. 19 folly::IOBuf 분석 — zero-copy buffer chain의 기본 단위
  20. 20 folly::IOBufQueue — chain의 push/pull 추상화
  21. 21 folly::io::Cursor·RWCursor — chain 위의 stream
  22. 22 folly Zero-copy 패턴 — IOBuf로 ScatterGather I/O 표현
  23. 23 folly::IOBuf shared semantics — clone·unshare·takeOwnership
  24. 24 folly::FBString 분석 — SSO + COW 구현
  25. 25 folly의 fmt::format 통합 — 모던 포맷팅 채택
  26. 26 folly::StringPiece — string_view 호환 분석
  27. 27 folly Join·Split utilities — 문자열 분해와 결합
  28. 28 folly::to·tryTo — text↔num 변환 분석
  29. 29 folly Conv Customization — 사용자 타입 지원
  30. 30 folly Conv 성능 비교 — sprintf·stringstream 대비
  31. 31 folly::F14ValueMap vs std::unordered_map
  32. 32 folly::F14NodeMap — stable pointer가 필요할 때
  33. 33 folly::F14VectorMap — cache-friendly iteration
  34. 34 folly::F14FastMap — auto-select 동작
  35. 35 folly F14 internals — SIMD probing 메커니즘
  36. 36 folly::small_vector — inline storage 분석
  37. 37 folly::FixedString — compile-time string
  38. 38 folly::AtomicHashMap — lock-free read 분석
  39. 39 folly::ConcurrentHashMap — sharded 동시 해시 맵
  40. 40 folly::EvictingCacheMap — LRU 구현 분석
  41. 41 folly::Synchronized — lock wrapper 패턴
  42. 42 folly::SharedMutex 분석
  43. 43 folly::Baton — one-shot wait 동기화
  44. 44 folly::RWSpinLock 분석
  45. 45 folly::PicoSpinLock — 1-byte spinlock
  46. 46 folly::ProducerConsumerQueue — SPSC 큐 분석
  47. 47 folly::MPMCQueue — multi-producer multi-consumer
  48. 48 folly::UnboundedQueue — 동적 크기 lock-free
  49. 49 folly::fibers::Channel — Go-like channel
  50. 50 folly::dynamic — JSON-like dynamic type 분석
  51. 51 folly JSON conversion — toJson·parseJson
  52. 52 folly dynamic ↔ struct — manual marshaling
  53. 53 folly dynamic Visitor pattern — type별 분기
  54. 54 folly::Singleton vs Meyers/static — 왜 Folly의 Singleton인가
  55. 55 folly::SingletonVault 분석 — 등록·소멸·의존성
  56. 56 folly::Singleton try_get·try_get_fast — TLS-cached 접근
  57. 57 folly::ExceptionWrapper — type-erased exception holder
  58. 58 folly::ScopeGuard·SCOPE_EXIT — RAII cleanup
  59. 59 folly::Optional vs std::optional
  60. 60 folly::Function vs std::function
  61. 61 folly::Lazy — 지연 초기화 wrapper
  62. 62 folly Meta 스타일 code review 패턴
  63. 63 folly anti-patterns — 잘못 쓰면 std보다 느림
  64. 64 folly vs std 선택 기준 분석
  65. 65 folly::coro 개요 — production C++20 코루틴 어댑터
  66. 66 folly::coro::Task — lazy single-shot 코루틴
  67. 67 folly::coro::AsyncGenerator — 비동기 스트림
  68. 68 folly coro blockingWait·collectAll — 동기 경계와 fan-in
  69. 69 folly::coro::Baton·Mutex — 코루틴-aware 동기화
  70. 70 folly::Expected — 결과 또는 오류
  71. 71 folly::Try — Future 결과 wrapper
  72. 72 folly::Try vs Expected 선택 기준
  73. 73 folly::Range — 일반 iterator pair
  74. 74 folly::Uri — URL 파서
  75. 75 folly Fingerprint64·128 — 분산 hash
  76. 76 folly SpookyHashV2 — fast non-crypto hash
  77. 77 folly::Init — main() 부트스트랩
  78. 78 folly::Indestructible — global lifetime 패턴
  79. 79 folly::MicroLock — 1-byte 락
  80. 80 folly::MicroSpinLock — 가장 좁은 spin lock
  81. 81 folly::format — legacy formatter 분석
  82. 82 folly::demangle — typeid 디망글링
  83. 83 folly::DynamicConverter — dynamic ↔ struct
  84. 84 folly::RecordIO — append-only 로그 파일 포맷
  85. 85 folly::io::Compression — zstd·lz4·snappy wrapper
  86. 86 folly::AsyncIO — io_uring·Linux AIO
  87. 87 folly::CancellationToken — 코루틴·Future 취소 전파
  88. 88 folly::observer — hot config의 atomic refresh
  89. 89 fbcode 패턴 모음 — folly 사용의 실전