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

folly::Try — Future 결과 wrapper

· Hawk · 3분 읽기

한 줄 요약: Try<T>는 정상값, 예외, 빈 상태 셋 중 하나를 담는다. Expected가 도메인 오류 표현이라면 Try예외 객체를 값으로 들고 다닐 때 쓴다. Futures 내부의 결과 슬롯.

#동기

Future/Task가 완료될 때 호출자는 두 가지 결과 중 하나를 받는다.

  • 정상 결과 T.
  • 비정상 — 예외 객체.

이 둘을 같은 슬롯에 담으려면 두 가지 해법이 있다.

  1. 변종 인터페이스 (Expected) — 도메인 오류 타입 E를 둔다. 그러나 임의 예외 타입을 그대로 받을 수 없다.
  2. 예외 객체를 값으로 보관 (Try)std::exception_ptr 또는 folly::exception_wrapper로 임의 예외를 값 형태로.

Future/coroutine 결과 슬롯은 어떤 예외든 받아야 하므로 Try가 적합하다.

folly::Try<int> t = compute();
if (t.hasValue()) use(*t);
else if (t.hasException()) handle(t.exception());
else /* empty */ // moved-from 또는 미설정

세 상태 모델이다. Expected의 empty 상태와 같은 이유 — moved-from 같은 일시적 무효 상태가 필요해서.

#API

#include <folly/Try.h>
folly::Try<int> t1{42}; // value
folly::Try<int> t2{folly::make_exception_wrapper<std::runtime_error>("oops")}; // exception
folly::Try<int> t3; // empty
// 상태 조회
t1.hasValue(); // true
t2.hasException(); // true
t3.hasValue(); // false
// 값 접근 — exception 상태면 throw
int v = t1.value(); // 42
int& vr = *t1;
int& vr2 = t1.value();
// 예외 접근
folly::exception_wrapper& ew = t2.exception();
// throw — exception 상태면 그 예외를 다시 throw, value 상태면 아무 일도 없음
t1.throwIfFailed();

Try<void> 도 일급. void 함수의 결과 슬롯에 쓴다.

#생성 방식

// 직접 값으로
folly::Try<int> a{10};
folly::Try<int> b{folly::in_place, 10};
// exception에서
folly::Try<int> c{folly::make_exception_wrapper<std::logic_error>("bad")};
// 람다 실행을 wrap — 정상이면 value, throw하면 exception 보관
auto t = folly::makeTryWith([&] { return riskyCompute(); });
// t는 hasValue 또는 hasException, throw가 호출자에게 전파되지 않음
// void 람다
auto tv = folly::makeTryWith([&] { riskyAction(); }); // Try<void>

makeTryWith가 가장 자주 쓴다. 예외를 catch해서 Try에 담는다는 한 줄 패턴.

#Futures와의 관계

// folly/futures/Future.h 약식
template <class T>
class Future {
public:
Try<T> getTry() &&; // 결과 또는 예외를 Try로 추출
T get() &&; // exception이면 throw
template <class F>
Future<R> thenTry(F&& fn); // callback이 Try<T>를 받음
};

thenTry는 callback이 Try<T>를 받는다. value/exception을 같은 함수로 처리하고 싶을 때 쓴다.

compute()
.thenTry([](folly::Try<int>&& t) {
if (t.hasException()) {
LOG(WARNING) << "compute failed: " << t.exception().what();
return -1;
}
return *t * 2;
});

thenValue(value만)와 thenError(exception만)가 합쳐진 형태가 thenTry.

코루틴에서도 비슷한 패턴:

auto t = co_await folly::coro::co_awaitTry(MaybeFails());
if (t.hasException()) { ... } else { use(*t); }

co_awaitTryTry<T>로 받는다. 예외 throw가 control flow에서 흔하면 이 형태가 가독성·성능 모두 낫다.

#내부 구조

// folly/Try.h 약식
template <class T>
class Try {
public:
enum class Contains { VALUE, EXCEPTION, NOTHING };
private:
Contains contains_ = Contains::NOTHING;
union Storage {
T value_;
folly::exception_wrapper ew_;
Storage() {}
~Storage() {}
};
Storage storage_;
void destroy() noexcept {
if (contains_ == Contains::VALUE) storage_.value_.~T();
else if (contains_ == Contains::EXCEPTION) storage_.ew_.~exception_wrapper();
contains_ = Contains::NOTHING;
}
};

핵심은 두 가지.

  1. discriminated unionvalue_ 또는 ew_ 둘 중 하나가 active. contains_가 어느 쪽인지 표시.
  2. exception_wrapperstd::exception_ptr보다 풍부한 wrapper. 다음 절에서 본다.

#exception_wrapper — 왜 별도 타입인가

std::exception_ptropaque 핸들이다. 예외 타입·메시지를 보려면 rethrow_exception + catch가 필요하다. log 한 줄 찍기에 무거운 비용.

folly::exception_wrapper는 wrapper 객체 자체에 type info, what() 캐시를 들고 다닌다.

folly::exception_wrapper ew = folly::make_exception_wrapper<std::runtime_error>("bad");
LOG(ERROR) << ew.what(); // throw 없이 message 추출
LOG(ERROR) << ew.class_name(); // 타입 이름
if (ew.is_compatible_with<std::runtime_error>()) {
ew.with_exception([](const std::runtime_error& e) {
// type-safe handle
});
}

std::exception_ptr은 throw/catch 없이 정보를 못 꺼낸다. exception_wrapper는 메타정보를 wrapper 안에 직접 보유해 비용 없는 introspection이 가능하다.

이게 Futures가 Try<T> 안에서 예외를 들고 다닐 수 있는 기반이다. throw/catch 비용 없이 callback chain을 통과한다.

#Try

folly::Try<void> t = folly::makeTryWith([] { doIt(); });
if (t.hasException()) handle(t.exception());

Try<void>value()가 의미 없지만 hasValue() == true일 수는 있다(정상 완료). void async 결과를 같은 인터페이스로 다루기 위한 일급.

#std와의 비교

항목std::exception_ptrfolly::exception_wrapperfolly::Try
역할예외 캐리어예외 캐리어 + 메타결과 슬롯
message 접근throw 후 catch직접 .what().exception().what()
타입 introspection안 됨.exception().is_compatible_with<E>()
결과 + 예외 동시표현 안 됨표현 안 됨표현됨
표준C++11follyfolly

C++23에서도 std::expectedT 또는 E (보통 enum) 두 갈래 모델만 표준화. 임의 예외를 값처럼 들고 다니는 표준 도구는 아직 없다.

#코드 리뷰 포인트

  • Try 만들고 즉시 *t — exception 상태에서 throw. 분기 필수.
  • callback이 Try 받는데 hasException 분기를 안 두면 silent swallow.
  • Try를 멤버로 보관 — moved-from(empty)인지 항상 확인해야.
  • exception_wrapper의 with_exception<E>(...)가 매치 안 되면 콜백이 실행되지 않는다 — fallback 필요.

#자주 보는 안티패턴

// 1. Try를 unwrap 강제
int v = t.value(); // empty 또는 exception이면 throw
// 2. exception_wrapper를 throw해서 다시 catch
try { t.exception().throw_exception(); }
catch (const std::runtime_error& e) { /* ... */ }
// → with_exception<std::runtime_error>(handler)로 throw 없이
// 3. Try<T>를 Expected처럼 사용 (도메인 오류 표현)
folly::Try<int> ParseInt(folly::StringPiece s); // 의미가 어색하다
// 예외 throw가 정말 흔하면 Expected<int, ParseError> 가 옳다

#정리

  • Try<T>는 value/exception/empty 세 상태의 결과 슬롯이다.
  • Future/coroutine 내부에서 결과를 보관하는 표준 wrapper.
  • exception_wrapper로 throw/catch 없이 예외 메타정보 접근.
  • thenTry, co_awaitTry로 value와 exception을 같은 분기에서 처리.
  • 도메인 오류 표현(Expected)과는 다른 용도 — 다음 절에서 정리.

#다음 편

Part 16-03: Try vs Expected에서 두 타입의 선택 기준을 정리한다.

#관련 항목

Folly Code Review · 71 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 사용의 실전