missing keys should throw InvalidNode, not BadConversion

Fixes GH #1274
This commit is contained in:
Reini Urban
2024-11-01 13:29:36 +01:00
committed by Jesse Beder
parent c2bec4c755
commit 3d2888cc8a
2 changed files with 12 additions and 2 deletions

View File

@@ -124,8 +124,8 @@ struct as_if<T, void> {
const Node& node;
T operator()() const {
if (!node.m_pNode)
throw TypedBadConversion<T>(node.Mark());
if (!node.m_pNode) // no fallback
throw InvalidNode(node.m_invalidKey);
T t;
if (convert<T>::decode(node, t))
@@ -140,6 +140,8 @@ struct as_if<std::string, void> {
const Node& node;
std::string operator()() const {
if (node.Type() == NodeType::Undefined) // no fallback
throw InvalidNode(node.m_invalidKey);
if (node.Type() == NodeType::Null)
return "null";
if (node.Type() != NodeType::Scalar)

View File

@@ -191,6 +191,14 @@ TEST(NodeTest, MapElementRemoval) {
EXPECT_TRUE(!node["foo"]);
}
TEST(NodeTest, MissingKey) {
Node node;
node["foo"] = "value";
EXPECT_TRUE(!node["bar"]);
EXPECT_EQ(NodeType::Undefined, node["bar"].Type());
EXPECT_THROW(node["bar"].as<std::string>(), InvalidNode);
}
TEST(NodeTest, MapIntegerElementRemoval) {
Node node;
node[1] = "hello";