Skip to content

Commit

Permalink
improve error messages when probing JSON path value type
Browse files Browse the repository at this point in the history
  • Loading branch information
schlimmchen committed Jul 15, 2024
1 parent 9e7a0bc commit 926a0b9
Showing 1 changed file with 11 additions and 3 deletions.
14 changes: 11 additions & 3 deletions src/Utils.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,12 @@ std::optional<float> getFromString(char const* val)
return res;
}

template<typename T>
char const* getTypename();

template<>
char const* getTypename<float>() { return "float"; }

template<typename T>
std::pair<T, String> Utils::getJsonValueByPath(JsonDocument const& root, String const& path)
{
Expand Down Expand Up @@ -179,15 +185,17 @@ std::pair<T, String> Utils::getJsonValueByPath(JsonDocument const& root, String
}

if (!value.is<char const*>()) {
snprintf(errBuffer, kErrBufferSize, "Value '%s' at JSON path '%s' is not "
"of the expected type", value.as<String>().c_str(), path.c_str());
snprintf(errBuffer, kErrBufferSize, "Value '%s' at JSON path '%s' is "
"neither a string nor of type %s", value.as<String>().c_str(),
path.c_str(), getTypename<T>());
return { T(), String(errBuffer) };
}

auto res = getFromString<T>(value.as<char const*>());
if (!res.has_value()) {
snprintf(errBuffer, kErrBufferSize, "String '%s' at JSON path '%s' cannot "
"be converted to the expected type", value.as<String>().c_str(), path.c_str());
"be converted to %s", value.as<String>().c_str(), path.c_str(),
getTypename<T>());
return { T(), String(errBuffer) };
}

Expand Down

0 comments on commit 926a0b9

Please sign in to comment.