diff --git a/doc/basics.md b/doc/basics.md index 9146a077f..828448475 100644 --- a/doc/basics.md +++ b/doc/basics.md @@ -1149,6 +1149,28 @@ int main(void) { } ``` + +You can do handle errors gracefully as well... + +```C++ +#include +#include "simdjson.h" +int main(void) { + simdjson::ondemand::parser parser; + simdjson::padded_string json_string; + simdjson::ondemand::document doc; + try { + json_string = padded_string::load("twitter.json"); + doc = parser.iterate(json_string); + uint64_t identifier = doc["statuses"].at(0)["id"]; + std::cout << identifier << std::endl; + } catch (simdjson::simdjson_error &error) { + std::cerr << "JSON error: " << error.what() << " near " + << doc.current_location() << " in " << json_string << std::endl; + } +} +``` + ### Current location in document Sometimes, it might be helpful to know the current location in the document during iteration. This is especially useful when encountering errors. The `current_location()` method on a diff --git a/tests/ondemand/ondemand_readme_examples.cpp b/tests/ondemand/ondemand_readme_examples.cpp index 8717923eb..ccd5f9a75 100644 --- a/tests/ondemand/ondemand_readme_examples.cpp +++ b/tests/ondemand/ondemand_readme_examples.cpp @@ -974,6 +974,22 @@ int load_example_except() { std::cout << identifier << std::endl; return EXIT_SUCCESS; } +int load_example_except_morecomplete(void) { + TEST_START(); + simdjson::ondemand::parser parser; + simdjson::padded_string json_string; + simdjson::ondemand::document doc; + try { + json_string = padded_string::load("twitter.json"); + doc = parser.iterate(json_string); + uint64_t identifier = doc["statuses"].at(0)["id"]; + std::cout << identifier << std::endl; + } catch (simdjson::simdjson_error &error) { + std::cerr << "JSON error: " << error.what() << " near " + << doc.current_location() << " in " << json_string << std::endl; + } + return EXIT_SUCCESS; +} #endif bool test_load_example() { TEST_START();