Skip to content

Best way to catch errors when querying json #2150

@apivovarov

Description

@apivovarov

I need to create API to return item name if item is found or nullptr if not.
What is the best way to do it if all json layers are optional? Should I check if every single layer exist and array index is in range? Or should I try to query json and catch particular exception(s) which indicate that item does not exist or array index is our of range in json

// Returns nullptr if name is not in json or index is out of range
const char* GetName(const int index) const {
    return json["Product"]["Suppliers"][index]["name"]
        .get_ref<const std::string&>()
        .c_str();
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions