Skip to content

Commit

Permalink
Add formatter for std::exception
Browse files Browse the repository at this point in the history
Co-authored-by: fekir <[email protected]>
Co-authored-by: Alexey Ochapov <[email protected]>
  • Loading branch information
3 people committed Aug 27, 2022
1 parent a337011 commit f40db2f
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 2 deletions.
19 changes: 18 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,22 @@ struct formatter<
}
};
FMT_END_NAMESPACE
#endif

#endif // __cpp_lib_variant

FMT_BEGIN_NAMESPACE
template <typename Char, typename T>
struct formatter<T, Char,
std::enable_if_t<std::is_base_of_v<std::exception, T>>>
: formatter<basic_string_view<Char>> {
template <typename FormatContext>
auto format(const std::exception& ex, FormatContext& ctx) const ->
typename FormatContext::iterator {
auto out = ctx.out();
detail::write(out, ex.what());
return out;
}
};
FMT_END_NAMESPACE

#endif // FMT_STD_H_
18 changes: 17 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,19 @@ TEST(std_test, variant) {
EXPECT_EQ(fmt::format("{}", v5), "variant(\"yes, this is variant\")");
#endif
}

TEST(std_test, exception) {
try {
std::vector<int> vec;
std::ignore = vec.at(42);
} catch (const std::exception& ex) {
EXPECT_EQ(fmt::format("{}", ex), "invalid vector subscript");
}

try {
std::vector<int> vec;
std::ignore = vec.at(42);
} catch (const std::out_of_range& ex) {
EXPECT_EQ(fmt::format("{}", ex), "invalid vector subscript");
}
}

0 comments on commit f40db2f

Please sign in to comment.