Add formatter for std::exception (#3062)

Co-authored-by: fekir <federico.kircheis@gmail.com>
Co-authored-by: Alexey Ochapov <alexez@alexez.com>
Co-authored-by: Vladislav Shchapov <vladislav@shchapov.ru>

Co-authored-by: fekir <federico.kircheis@gmail.com>
Co-authored-by: Alexey Ochapov <alexez@alexez.com>
Co-authored-by: Vladislav Shchapov <vladislav@shchapov.ru>
This commit is contained in:
Zach Toogood 2022-09-02 18:33:37 +03:00 committed by GitHub
parent 75383a87f9
commit 4191477b98
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 36 additions and 2 deletions

View File

@ -8,6 +8,7 @@
#ifndef FMT_STD_H_ #ifndef FMT_STD_H_
#define FMT_STD_H_ #define FMT_STD_H_
#include <exception>
#include <thread> #include <thread>
#include <type_traits> #include <type_traits>
#include <utility> #include <utility>
@ -166,6 +167,20 @@ struct formatter<
} }
}; };
FMT_END_NAMESPACE FMT_END_NAMESPACE
#endif #endif // __cpp_lib_variant
FMT_BEGIN_NAMESPACE
template <typename T, typename Char>
struct formatter<
T, Char,
typename std::enable_if<std::is_base_of<std::exception, T>::value>::type>
: formatter<string_view> {
template <typename FormatContext>
auto format(const std::exception& ex, FormatContext& ctx) const ->
typename FormatContext::iterator {
return fmt::formatter<string_view>::format(ex.what(), ctx);
}
};
FMT_END_NAMESPACE
#endif // FMT_STD_H_ #endif // FMT_STD_H_

View File

@ -6,11 +6,11 @@
// For the license information refer to format.h. // For the license information refer to format.h.
#include "fmt/std.h" #include "fmt/std.h"
#include "fmt/ranges.h"
#include <string> #include <string>
#include <vector> #include <vector>
#include "fmt/ranges.h"
#include "gtest/gtest.h" #include "gtest/gtest.h"
TEST(std_test, path) { TEST(std_test, path) {
@ -77,3 +77,22 @@ TEST(std_test, variant) {
EXPECT_EQ(fmt::format("{}", v5), "variant(\"yes, this is variant\")"); EXPECT_EQ(fmt::format("{}", v5), "variant(\"yes, this is variant\")");
#endif #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);
}
}