From 4191477b98de8d52497f9449c815fad895f43384 Mon Sep 17 00:00:00 2001 From: Zach Toogood Date: Fri, 2 Sep 2022 18:33:37 +0300 Subject: [PATCH] Add formatter for std::exception (#3062) Co-authored-by: fekir Co-authored-by: Alexey Ochapov Co-authored-by: Vladislav Shchapov Co-authored-by: fekir Co-authored-by: Alexey Ochapov Co-authored-by: Vladislav Shchapov --- include/fmt/std.h | 17 ++++++++++++++++- test/std-test.cc | 21 ++++++++++++++++++++- 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/include/fmt/std.h b/include/fmt/std.h index 41d2b283..c8b042a4 100644 --- a/include/fmt/std.h +++ b/include/fmt/std.h @@ -8,6 +8,7 @@ #ifndef FMT_STD_H_ #define FMT_STD_H_ +#include #include #include #include @@ -166,6 +167,20 @@ struct formatter< } }; FMT_END_NAMESPACE -#endif +#endif // __cpp_lib_variant + +FMT_BEGIN_NAMESPACE +template +struct formatter< + T, Char, + typename std::enable_if::value>::type> + : formatter { + template + auto format(const std::exception& ex, FormatContext& ctx) const -> + typename FormatContext::iterator { + return fmt::formatter::format(ex.what(), ctx); + } +}; +FMT_END_NAMESPACE #endif // FMT_STD_H_ diff --git a/test/std-test.cc b/test/std-test.cc index c22b3e38..b9c15e02 100644 --- a/test/std-test.cc +++ b/test/std-test.cc @@ -6,11 +6,11 @@ // For the license information refer to format.h. #include "fmt/std.h" -#include "fmt/ranges.h" #include #include +#include "fmt/ranges.h" #include "gtest/gtest.h" TEST(std_test, path) { @@ -77,3 +77,22 @@ TEST(std_test, variant) { EXPECT_EQ(fmt::format("{}", v5), "variant(\"yes, this is variant\")"); #endif } + +TEST(std_test, exception) { + std::string str("Test Exception"); + std::string escstr = fmt::format("\"{}\"", str); + + try { + throw std::runtime_error(str); + } catch (const std::exception& ex) { + EXPECT_EQ(fmt::format("{}", ex), str); + EXPECT_EQ(fmt::format("{:?}", ex), escstr); + } + + try { + throw std::runtime_error(str); + } catch (const std::runtime_error& ex) { + EXPECT_EQ(fmt::format("{}", ex), str); + EXPECT_EQ(fmt::format("{:?}", ex), escstr); + } +}