Skip to content

Commit

Permalink
missing keys should throw InvalidNode, not BadConversion
Browse files Browse the repository at this point in the history
Fixes GH jbeder#1274
  • Loading branch information
Reini Urban committed Nov 1, 2024
1 parent c2bec4c commit d9c3a6d
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 2 deletions.
6 changes: 4 additions & 2 deletions include/yaml-cpp/node/impl.h
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand All @@ -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)
Expand Down
8 changes: 8 additions & 0 deletions test/node/node_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down

0 comments on commit d9c3a6d

Please sign in to comment.