This commit is contained in:
nlohmann committed 2026-10-12 07:35:31 +00:00
1 parent 79119509a9
commit 22fba27145
555 files changed
+17342 -1394

No files matched your search

+81 -6
View File
@@ -46,13 +46,34 @@ When the macro is not defined, the library will define it to its default value.
??? example "Example: default behavior"
```cpp
--8<-- "examples/diagnostics_standard.cpp"
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
json j;
j["address"]["street"] = "Fake Street";
j["address"]["housenumber"] = "12";
try
{
int housenumber = j["address"]["housenumber"];
}
catch (const json::exception& e)
{
std::cout << e.what() << '\n';
}
}
```
Output:
```
--8<-- "examples/diagnostics_standard.output"
[json.exception.type_error.302] type must be number, but is string
```
This exception can be hard to debug if storing the value `#!c "12"` and accessing it is further apart.
@@ -60,13 +81,36 @@ When the macro is not defined, the library will define it to its default value.
??? example "Example: extended diagnostic messages"
```cpp
--8<-- "examples/diagnostics_extended.cpp"
#include <iostream>
# define JSON_DIAGNOSTICS 1
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
json j;
j["address"]["street"] = "Fake Street";
j["address"]["housenumber"] = "12";
try
{
int housenumber = j["address"]["housenumber"];
}
catch (const json::exception& e)
{
std::cout << e.what() << '\n';
}
}
```
Output:
```
--8<-- "examples/diagnostics_extended.output"
[json.exception.type_error.302] (/address/housenumber) type must be number, but is string
```
Now the exception message contains a JSON Pointer `/address/housenumber` that indicates which value has the wrong type.
@@ -74,13 +118,44 @@ When the macro is not defined, the library will define it to its default value.
??? example "Example: using only diagnostic positions in exceptions"
```cpp
--8<-- "examples/diagnostic_positions_exception.cpp"
#include <iostream>
#define JSON_DIAGNOSTIC_POSITIONS 1
#include <nlohmann/json.hpp>
using json = nlohmann::json;
/* Demonstration of type error exception with diagnostic positions support enabled */
int main()
{
//Invalid json string - housenumber type must be int instead of string
const std::string json_invalid_string = R"(
{
"address": {
"street": "Fake Street",
"housenumber": "1"
}
}
)";
json j = json::parse(json_invalid_string);
try
{
int housenumber = j["address"]["housenumber"];
std::cout << housenumber;
}
catch (const json::exception& e)
{
std::cout << e.what() << '\n';
}
}
```
Output:
```
--8<-- "examples/diagnostic_positions_exception.output"
[json.exception.type_error.302] (bytes 92-95) type must be number, but is string
```
The output shows the exception with start/end positions only.