improve jsonvalidation type errors

This commit is contained in:
HJfod 2024-08-23 23:35:29 +03:00
parent 908ac44a0b
commit 35d16eb44e
2 changed files with 24 additions and 14 deletions

View file

@ -305,6 +305,8 @@ namespace geode {
JsonExpectedValue();
JsonExpectedValue(Impl* from, matjson::Value& scope, std::string_view key);
static const char* matJsonTypeToString(matjson::Type ty);
bool hasError() const;
void setError(std::string_view error);
@ -323,11 +325,19 @@ namespace geode {
}
else {
try {
if (this->getJSONRef().template is<T>()) {
return this->getJSONRef().template as<T>();
}
else {
this->setError(
"unexpected type {}",
this->matJsonTypeToString(this->getJSONRef().type())
);
}
}
// matjson can throw variant exceptions too so you need to do this
catch(std::exception const& e) {
this->setError("invalid json type: {}", e);
this->setError("unable to parse json: {}", e);
}
}
return std::nullopt;

View file

@ -161,18 +161,6 @@ JsonMaybeValue JsonChecker::root(std::string const& hierarchy) {
return JsonMaybeValue(*this, m_json, hierarchy, true);
}
static const char* matJsonTypeToString(matjson::Type ty) {
switch (ty) {
case matjson::Type::Null: return "null";
case matjson::Type::Bool: return "bool";
case matjson::Type::Number: return "number";
case matjson::Type::String: return "string";
case matjson::Type::Array: return "array";
case matjson::Type::Object: return "object";
default: return "unknown";
}
}
// This is used for null JsonExpectedValues (for example when doing
// `json.has("key")` where "key" doesn't exist)
static matjson::Value NULL_SCOPED_VALUE = nullptr;
@ -231,6 +219,18 @@ JsonExpectedValue::~JsonExpectedValue() {}
JsonExpectedValue::JsonExpectedValue(JsonExpectedValue&&) = default;
JsonExpectedValue& JsonExpectedValue::operator=(JsonExpectedValue&&) = default;
const char* JsonExpectedValue::matJsonTypeToString(matjson::Type ty) {
switch (ty) {
case matjson::Type::Null: return "null";
case matjson::Type::Bool: return "bool";
case matjson::Type::Number: return "number";
case matjson::Type::String: return "string";
case matjson::Type::Array: return "array";
case matjson::Type::Object: return "object";
default: return "unknown";
}
}
matjson::Value const& JsonExpectedValue::getJSONRef() const {
return m_impl->scope;
}