#include #include #include #include #include namespace leaf = boost::leaf; struct EFailureInfo { std::string value; }; enum CustomErrorCode { first_error = 1, second_error }; namespace boost { namespace leaf { template <> struct is_error_type : std::true_type {}; template <> struct is_error_type : std::true_type {}; } // namespace leaf } // namespace boost void f1(unsigned behavior) { [[maybe_unused]] auto propagate = leaf::preload(EFailureInfo{"f1"}); switch (behavior) { case 0: return; case 1: throw std::runtime_error("f1-1"); case 2: throw std::bad_alloc(); default: break; } } leaf::result f2(unsigned behavior) { if (behavior == 0) { return leaf::new_error(first_error); } if (behavior == 1) { throw std::runtime_error("f2-1"); } [[maybe_unused]] auto propagate = leaf::preload(EFailureInfo{"f2"}); switch (behavior) { case 0: break; case 1: break; case 2: return leaf::new_error(second_error); case 3: throw std::runtime_error("f2-2"); case 4: return leaf::new_error(std::make_error_code(std::errc::address_in_use)); default: f1(behavior - 5); break; } return behavior; } int main() { for (unsigned i = 0; i < 10; ++i) { std::cout << "\nf2(" << i << ")" << std::endl; leaf::result result = leaf::try_( [i]() -> leaf::result { LEAF_CHECK(f2(i)); std::cout << "Success" << std::endl; return 0; }, [](leaf::catch_ e, EFailureInfo const &info) -> leaf::result { std::cout << "Error: runtime_error: " << e.value.what() << " info: " << info.value << std::endl; return -1; }, [](leaf::catch_ e) -> leaf::result { std::cout << "Error: runtime_error: " << e.value.what() << std::endl; return -2; }, [](CustomErrorCode ec, EFailureInfo const &info) -> leaf::result { std::cout << "Error: code: " << ec << " info: " << info.value << std::endl; return -3; }, [](CustomErrorCode ec) -> leaf::result { std::cout << "Error: code: " << ec << std::endl; return -4; }, #if 0 [](leaf::error_info const &e, leaf::verbose_diagnostic_info const &v) -> leaf::result { std::cout << "Error: unmatched error what: " << (e.has_exception() ? e.exception()->what() : "") << " verbose-info: \n" << v << std::endl; return -5; }); #else [](leaf::error_info const &e) -> leaf::result { std::cout << "Error: unmatched error what: " << (e.has_exception() ? e.exception()->what() : "") << std::endl; return -5; }); #endif } return 0; }