Skip to content

Commit 7b52938

Browse files
authored
Improve bad access error for std::expected<T, rfl::Error> (#558)
1 parent c732e45 commit 7b52938

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

include/rfl/Result.hpp

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -445,4 +445,22 @@ inline Unexpected<Error> error(const Error& _err) {
445445

446446
} // namespace rfl
447447

448+
#ifdef REFLECTCPP_USE_STD_EXPECTED
449+
template <>
450+
class std::bad_expected_access<rfl::Error> : public bad_expected_access<void> {
451+
public:
452+
explicit constexpr bad_expected_access(rfl::Error er) : err_(std::move(er)) {}
453+
const char* what() const noexcept override { return err_.what().c_str(); }
454+
455+
template <typename Self>
456+
[[nodiscard]]
457+
auto error(this Self&& self) noexcept {
458+
return std::forward<Self>(self).err_;
459+
}
460+
461+
private:
462+
rfl::Error err_;
463+
};
448464
#endif
465+
466+
#endif
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
#ifdef REFLECTCPP_USE_STD_EXPECTED
2+
#include <expected>
3+
#endif
4+
5+
#include <rfl.hpp>
6+
#include <gtest/gtest.h>
7+
8+
namespace test_exceptions {
9+
10+
struct Person {
11+
rfl::Rename<"firstName", std::string> first_name;
12+
rfl::Rename<"lastName", std::string> last_name = "Flanders";
13+
};
14+
15+
TEST(generic, test_exceptions) {
16+
const std::string error_message = "unified bad access message!";
17+
#ifdef REFLECTCPP_USE_STD_EXPECTED
18+
rfl::Result<Person> person = std::unexpected(rfl::Error(error_message));
19+
#else
20+
rfl::Result<Person> person(rfl::error(error_message));
21+
#endif
22+
23+
try {
24+
person.value();
25+
FAIL() << "Expected an exception!";
26+
}
27+
#ifdef REFLECTCPP_USE_STD_EXPECTED
28+
catch (std::bad_expected_access<rfl::Error> const& err) {
29+
EXPECT_EQ(err.what(), error_message);
30+
}
31+
#else
32+
catch (std::runtime_error const& err) {
33+
EXPECT_EQ(err.what(), error_message);
34+
}
35+
#endif
36+
catch (...) {
37+
FAIL() << "Invalid exception type!";
38+
}
39+
}
40+
} // namespace test_exceptions

0 commit comments

Comments
 (0)