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

folly::ExceptionWrapper — type-erased exception holder

· Hawk · 4분 읽기

#한 줄 요약

folly::exception_wrapperexception을 throw 없이 holding/copying/inspecting할 수 있는 type-erased 컨테이너다. std::exception_ptr보다 가볍고 효율적이며, throw 없이 type 정보를 검사할 수 있다. Future, Try, 모든 비동기 API의 error 통로다.

#동기 — std::exception_ptr의 한계

C++11의 std::exception_ptr는 exception을 capture해서 옮길 수 있다.

std::exception_ptr ep;
try { throw std::runtime_error("oops"); }
catch (...) { ep = std::current_exception(); }
// 다른 스레드에서
try { std::rethrow_exception(ep); }
catch (const std::exception& e) { LOG(ERROR) << e.what(); }

문제.

  1. type 검사 불가 — what을 얻거나 type을 알려면 rethrow + catch 필요. throw가 비싸다(100us 단위).
  2. string 메시지 직접 추출 불가 — what() 호출하려면 catch 안에 있어야 함.
  3. copy 비용 — exception_ptr는 atomic refcount의 shared_ptr 비슷한 구조.

비동기 코드(Future chain)는 error를 자주 옮기고 검사한다. 매번 throw하면 너무 느리다.

#exception_wrapper

#include <folly/ExceptionWrapper.h>
folly::exception_wrapper ew = folly::make_exception_wrapper<std::runtime_error>("oops");
// throw 없이 검사
if (ew.is_compatible_with<std::runtime_error>()) {
LOG(ERROR) << ew.class_name() << ": " << ew.what();
}
// 핸들러로 분기 (throw 없이)
ew.handle(
[](const std::runtime_error& e) { handleRuntime(e); },
[](const std::exception& e) { handleStd(e); },
[] { handleUnknown(); }
);
// 필요하면 throw
ew.throw_exception();

핵심.

  • type 정보를 wrapper 안에 저장 → throw 없이 검사.
  • what()도 throw 없이 호출.
  • handle() 헬퍼로 type별 분기.
  • 진짜 throw가 필요한 경계에서만 throw_exception().

#내부 구현 — 3가지 저장 모드

class exception_wrapper {
enum Mode { Empty, Inline, Exception_Ptr };
Mode mode_;
union {
InlineStorage inline_; // SBO — 작은 exception은 인라인
std::exception_ptr eptr_; // 큰 경우 fallback
};
const std::type_info* type_; // type 정보
std::string what_; // 미리 추출
};
  • Inline mode: std::runtime_error 같은 작은 표준 예외는 wrapper 안에 직접 저장(SBO). copy가 단순 memcpy.
  • Exception_Ptr mode: 큰 사용자 정의 예외는 exception_ptr로.
  • Empty mode: 예외 없음.

type 정보와 what string을 미리 뽑아 두므로 검사가 빠르다.

#사용 패턴

#Try / Future error 통로

folly::Future<int> compute() {
return folly::makeFuture<int>(folly::exception_wrapper(
std::runtime_error("bad")));
}
future.thenTry([](folly::Try<int> t) {
if (t.hasException()) {
auto& ew = t.exception(); // exception_wrapper&
LOG(ERROR) << ew.what();
}
});

#handle로 type별 분기

ew.handle(
[](const std::system_error& e) { /* OS error */ },
[](const std::runtime_error& e) { /* logic error */ },
[](const std::exception& e) { /* generic */ },
[] { /* non-std exception */ }
);

순서대로 매칭, 첫 일치 핸들러 실행. 마지막 빈 람다는 catch(…)에 해당.

#with_exception — 한 type만

ew.with_exception([](const std::runtime_error& e) {
LOG(ERROR) << e.what();
}); // 다른 type이면 false 반환

#std::exception_ptr 비교

exception_ptrexception_wrapper
copy 비용atomic refcountinline mode면 memcpy
type 검사rethrow 필요throw 없이
what()rethrow + catch직접 호출
핸들러 매칭rethrow + catchhandle()로 표 매칭
empty 표현nullptrEmpty mode

#코드 리뷰 포인트

#1. async error 통로는 exception_wrapper 사용

// 회피 — async에서 throw
folly::Future<int> f = doAsync().then([] {
throw std::runtime_error("oops"); // future가 잡아 exception_ptr로 변환
});
// Good — exception_wrapper로 직접
folly::Future<int> f = folly::makeFuture<int>(
folly::make_exception_wrapper<std::runtime_error>("oops"));

직접 wrapper로 만들면 throw 비용이 안 듦.

#2. handle 사용 시 base type을 마지막에

// 회피 — base가 먼저
ew.handle(
[](const std::exception& e) { ... }, // 모든 std::exception 매칭
[](const std::runtime_error& e) { ... } // 절대 도달 안 함
);
// Good — derived가 먼저
ew.handle(
[](const std::runtime_error& e) { ... },
[](const std::exception& e) { ... }
);

위에서 아래로 매칭하므로 더 구체적인 type을 먼저.

#3. with_exception 결과 무시

// 회피
ew.with_exception([](const std::runtime_error& e) { ... });
// runtime_error가 아니면 silent
// Good
if (!ew.with_exception(...)) {
LOG(WARNING) << "Unexpected exception: " << ew.class_name();
}

특정 type만 처리하면 나머지 type을 어떻게 할지 명시.

#4. throw_exception을 마지막 boundary에서만

// API boundary
int doWork() {
auto result = futureWork().get(); // Try<int>
if (result.hasException()) {
result.exception().throw_exception(); // 여기서만 throw
}
return result.value();
}

내부는 wrapper로 들고 다니다가 caller에게 던질 때만 throw.

#안티패턴

#1. catch에서 매번 exception_wrapper 생성

// 회피 — 콜백마다 wrapper 생성
.thenTry([](folly::Try<int> t) {
if (t.hasException()) {
auto ew = folly::exception_wrapper(t.exception()); // 이미 wrapper인데 wrap
}
});
// Good
.thenTry([](folly::Try<int> t) {
if (t.hasException()) {
auto& ew = t.exception(); // 이미 wrapper
}
});

#2. wrapper에서 throw → catch → wrapper로 복사

// 회피 — 왕복
try { ew.throw_exception(); }
catch (...) { auto ew2 = folly::exception_wrapper(); ... }

wrapper로 들고 가면 throw/catch가 필요 없다. round-trip은 정확히 wrapper가 피하려는 비용.

#3. 모든 예외를 std::exception base로 처리

// 회피
ew.with_exception([](const std::exception& e) { ... });
// 사용자 정의 비-std 예외 누락

비-std 예외(예: int, 사용자 클래스)는 base가 std::exception이 아니라 매칭 실패. handle로 catch-all 명시.

#정리

  • exception_wrapper는 throw 없이 type 검사 가능한 exception holder.
  • 작은 표준 예외는 inline (SBO), 큰 건 exception_ptr fallback.
  • handle()로 type별 분기, with_exception()으로 단일 type 처리.
  • async/thread 경계에서 throw 비용을 피한다.
  • 진짜 throw는 마지막 API boundary에서.
  • Try, Future의 error path가 모두 wrapper 위에서 동작.

#다음 편

Part 13-02 ScopeGuard — SCOPE_EXIT 매크로로 cleanup을 RAII로.

#관련 항목

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