Skip to content

Commit b4b6371

Browse files
samantharitterkevinAlbs
authored andcommitted
CXX-2143 throw an exception when getting types from an unset element
1 parent 604c11f commit b4b6371

File tree

2 files changed

+19
-4
lines changed

2 files changed

+19
-4
lines changed

src/bsoncxx/document/element.cpp

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -79,10 +79,14 @@ stdx::string_view element::key() const {
7979
return stdx::string_view{key};
8080
}
8181

82-
#define BSONCXX_ENUM(name, val) \
83-
types::b_##name element::get_##name() const { \
84-
types::bson_value::view v{_raw, _length, _offset, _keylen}; \
85-
return v.get_##name(); \
82+
#define BSONCXX_ENUM(name, val) \
83+
types::b_##name element::get_##name() const { \
84+
if (_raw == nullptr) { \
85+
throw bsoncxx::exception{error_code::k_unset_element, \
86+
"cannot get " #name " from an uninitialized element"}; \
87+
} \
88+
types::bson_value::view v{_raw, _length, _offset, _keylen}; \
89+
return v.get_##name(); \
8690
}
8791
#include <bsoncxx/enums/type.hpp>
8892
#undef BSONCXX_ENUM

src/bsoncxx/test/bson_types.cpp

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919

2020
#include <bsoncxx/builder/basic/array.hpp>
2121
#include <bsoncxx/builder/basic/document.hpp>
22+
#include <bsoncxx/document/element.hpp>
2223
#include <bsoncxx/stdx/string_view.hpp>
2324
#include <bsoncxx/test_util/catch.hh>
2425

@@ -28,6 +29,7 @@ using namespace bsoncxx;
2829
using namespace types;
2930
using bsoncxx::builder::basic::make_document;
3031
using bsoncxx::builder::basic::kvp;
32+
using bsoncxx::document::element;
3133

3234
TEST_CASE("type to_string", "[bsoncxx::type::to_string]") {
3335
REQUIRE(to_string(bsoncxx::type::k_bool) == "bool");
@@ -186,6 +188,15 @@ TEST_CASE("b_maxkey", "[bsoncxx::type::b_maxkey]") {
186188
REQUIRE(a == a);
187189
}
188190

191+
TEST_CASE("getting types from an uninitialized element throws", "[bsoncxx::document::element]") {
192+
element elem{};
193+
REQUIRE_THROWS(elem.get_value());
194+
195+
#define BSONCXX_ENUM(name, val) REQUIRE_THROWS(elem.get_##name());
196+
#include <bsoncxx/enums/type.hpp>
197+
#undef BSONCXX_ENUM
198+
}
199+
189200
TEST_CASE("bson_value::view returns correct type", "[bsoncxx::types::bson_value::view]") {
190201
b_bool bool_val{true};
191202
REQUIRE(bson_value::view{bool_val}.type() == bsoncxx::type::k_bool);

0 commit comments

Comments
 (0)