add: [imp] error_category.name

This commit is contained in:
mutouyun 2022-12-18 17:57:07 +08:00
parent 3aac7bea08
commit e60f856295
3 changed files with 21 additions and 4 deletions

View File

@ -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_

View File

@ -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 {

View File

@ -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), "]"));
}