diff --git a/include/libimp/error.h b/include/libimp/error.h index 7762aa0..1cc59bd 100644 --- a/include/libimp/error.h +++ b/include/libimp/error.h @@ -28,6 +28,7 @@ public: virtual ~error_category() noexcept = default; /// @brief observer + virtual std::string name() const = 0; virtual std::string message(result_code r) const = 0; /// @brief comparison function @@ -65,4 +66,14 @@ public: friend LIBIMP_EXPORT bool operator!=(error_code const &lhs, error_code const &rhs) noexcept; }; +/** + * @brief @brief Custom defined fmt_to method for imp::fmt + */ +namespace detail { + +inline bool tag_invoke(decltype(::LIBIMP::fmt_to), fmt_context &ctx, error_code r) noexcept { + return fmt_to(ctx, r.message()); +} + +} // namespace detail LIBIMP_NAMESPACE_END_ diff --git a/src/libimp/error.cpp b/src/libimp/error.cpp index 0b10a7f..7c4cafd 100644 --- a/src/libimp/error.cpp +++ b/src/libimp/error.cpp @@ -13,8 +13,11 @@ namespace { class generic_error_category : public error_category { public: + std::string name() const { + return "generic"; + } std::string message(result_code r) const { - return fmt("[", r.value(), (!r ? ", \"success\"]" : ", \"failure\"]")); + return fmt(r.value(), (!r ? ", \"success\"" : ", \"failure\"")); } }; @@ -44,7 +47,7 @@ error_category const &error_code::category() const noexcept { } std::string error_code::message() const { - return ec_->message(r_code_); + return fmt("[", ec_->name(), ": ", ec_->message(r_code_), "]"); } error_code::operator bool() const noexcept { diff --git a/test/imp/test_imp_error.cpp b/test/imp/test_imp_error.cpp index 08e0d1a..d985a3b 100644 --- a/test/imp/test_imp_error.cpp +++ b/test/imp/test_imp_error.cpp @@ -10,6 +10,9 @@ namespace { class custom_error_category : public imp::error_category { public: + std::string name() const { + return "custom"; + } std::string message(imp::result_code r) const { return !r ? "success" : "failure"; } @@ -21,11 +24,11 @@ TEST(error, error_code) { imp::error_code ecode; EXPECT_FALSE(ecode); std::cout << ecode.message() << "\n"; - EXPECT_EQ(ecode.message(), "[0, \"success\"]"); + EXPECT_EQ(ecode.message(), "[generic: 0, \"success\"]"); custom_error_category cec; ecode = {123, cec}; EXPECT_TRUE(ecode); std::cout << ecode.message() << "\n"; - EXPECT_EQ(ecode.message(), cec.message(123)); + EXPECT_EQ(ecode.message(), imp::fmt("[", cec.name(), ": ", cec.message(123), "]")); } \ No newline at end of file