Skip to content
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
42 changes: 39 additions & 3 deletions Source/LuaBridge/detail/Expected.h
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

#include <type_traits>
#include <memory>
#include <string>
#include <utility>

#if LUABRIDGE_HAS_EXCEPTIONS
Expand Down Expand Up @@ -62,6 +63,19 @@ struct is_nothrow_swappable
: std::is_nothrow_swappable_with<std::add_lvalue_reference_t<T>, std::add_lvalue_reference_t<T>>
{
};

template <class T, class = void>
struct has_member_message : std::false_type
{
};

template <class T>
struct has_member_message<T, std::void_t<decltype(std::declval<T>().message())>> : std::true_type
{
};

template <class T>
inline static constexpr bool has_member_message_v = has_member_message<T>::value;
} // namespace detail

template <class T, class E>
Expand Down Expand Up @@ -976,19 +990,41 @@ template <class E>
class BadExpectedAccess;

template <>
class BadExpectedAccess<void> : public std::exception
class BadExpectedAccess<void> : public std::runtime_error
{
template <class T>
friend class BadExpectedAccess;

BadExpectedAccess(std::in_place_t) noexcept
: std::runtime_error("Bad access to expected value")
{
}

public:
explicit BadExpectedAccess() noexcept
BadExpectedAccess() noexcept
: BadExpectedAccess(std::in_place)
{
}

explicit BadExpectedAccess(const std::string& message) noexcept
: std::runtime_error(message)
{
}
};

template <class E>
class BadExpectedAccess : public BadExpectedAccess<void>
{
public:
explicit BadExpectedAccess(E error) noexcept(std::is_nothrow_constructible_v<E, E&&>)
: error_(std::move(error))
: BadExpectedAccess<void>([](const E& error)
{
if constexpr (detail::has_member_message_v<E>)
return error.message();
else
return std::in_place;
}(error))
, error_(std::move(error))
{
}

Expand Down
22 changes: 22 additions & 0 deletions Tests/Source/Tests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -874,6 +874,28 @@ TEST_F(LuaBridgeTest, BooleanNoValue)
}

#if LUABRIDGE_HAS_EXCEPTIONS
TEST_F(LuaBridgeTest, StackExceptionWithMessage)
{
try {
auto result = luabridge::Stack<std::string>::get(L, 1);
result.value();
EXPECT_FALSE(true);
} catch (const std::exception& e) {
EXPECT_STREQ("The lua object can't be cast to desired type", e.what());
}
}

TEST_F(LuaBridgeTest, ExpectedExceptionWithoutMessage)
{
try {
luabridge::Expected<std::string, int> result = luabridge::makeUnexpected(5);
result.value();
EXPECT_FALSE(true);
} catch (const std::exception& e) {
EXPECT_STREQ("bad_expected_access", e.what());
}
}

namespace {
template <class... Args>
std::string call_callback_get_exception(const luabridge::LuaRef& fn, Args&&... args)
Expand Down