This sould work.
// some of them could be unnecessary. but it's woking like that.
#include <bsoncxx/builder/basic/array.hpp>
#include <bsoncxx/builder/basic/document.hpp>
#include <bsoncxx/document/value.hpp>
#include <bsoncxx/document/view.hpp>
#include <bsoncxx/json.hpp>
#include <bsoncxx/stdx/string_view.hpp>
#include <bsoncxx/types.hpp>
#include <bsoncxx/types/value.hpp>
#include <bsoncxx/exception/exception.hpp>
int main (int,char**){
std::string UnvalidJsonString =
"{ \"myKVP\" : \" blubb\",\"wrong\",\"right\":\"Jear!\"}";
// look here for more detailed error handling:
//https://github.com/mongodb/mongo-cxx-driver/commit/956cf608fc91cd191b5c53cc31e94d52df526d37
try{
auto UnvalidJsonBsonOpject = bsoncxx::from_json(UnvalidJsonString);
}
catch(bsoncxx::exception& e){
// this exception is thrown, when a invalid json is parsed.
std::cout << "Tried to pare a wring json: " << std::endl;
//e.waht() is returning a human readable message which says withe a drawed arrow, where the error occured.
std::cout << e.what() << std::endl;
std::cout << "------------------------------------- end error message" << std::endl;
}
And it is printing:
Tried to pare a wring json:
parse error: object key and value must be separated by a colon (':')
{ "myKVP" : " blubb","wrong","right":"Jear!"}
(right here) ------^
: could not parse JSON document
------------------------------------- end error message
I got there with the example opend in the repro in the examples section. Or her in the commit I accidentially found
here.Following looks trivial, but it's not obvious if you are searching for as an unscilled programmer...
if you look to any function of mongo/bson cxx, it is explained more ore less in doxygen documentation. but what is mentioned in there is the error, which is thrown, if the operation is failed. Errors are equal to the expression "exception". So here is telling me the documentation that
`bsoncxx::from_json` is throwing a `bsoncxx::exception` the mongocxx
-part is throwing much more difrent exception typs. keep that in mind and proove my words. I'm new to the cxx.
Hope you find this helpful and it will save you some time!
Greez javantamt