Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add formatter for std::exception #3062

Merged
merged 1 commit into from
Sep 2, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion include/fmt/std.h
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
#ifndef FMT_STD_H_
#define FMT_STD_H_

#include <exception>
#include <thread>
#include <type_traits>
#include <utility>
Expand Down Expand Up @@ -166,6 +167,20 @@ struct formatter<
}
};
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_
21 changes: 20 additions & 1 deletion test/std-test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@
// For the license information refer to format.h.

#include "fmt/std.h"
#include "fmt/ranges.h"

#include <string>
#include <vector>

#include "fmt/ranges.h"
#include "gtest/gtest.h"

TEST(std_test, path) {
Expand Down Expand Up @@ -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);
}
}