Skip to content

from_json declaration order and exceptions #561

Description

@andbleo

I am running into an issue where if a from_json function I wrote does a conversion that uses another from_json function I wrote, whether or not I can catch exceptions from nlohmann::json depends on the order of the from_json functions. Repro code below:

#include <exception>
#include <fstream>
#include <iostream>

#include "json.hpp"

struct A {
    int value;
};

struct B {
    A a;
};

void from_json(const nlohmann::json& j, B& b) {
    b.a = j.at("test").get<A>();
}

// If this is moved before the from_json for B, I can catch the exception below
void from_json(const nlohmann::json& j, A& a) {
    a.value = j.at("value").get<int>();
}

int main() {
    try {
        std::ifstream stream("test.json");
        nlohmann::json j;
        stream >> j;
        B b = j;
    } catch (const std::exception& e) {
        std::cerr << "caught exception: " << e.what() << std::endl;
    }
    return 0;
}

My test.json file is below:

{
    "test": {
        "value": "hello"
    }
}

In the above example, the output is:

libc++abi.dylib: terminating with uncaught exception of type std::domain_error: type must be number, but is string
Abort trap: 6

If I switch the order of the from_json functions, the output is as expected:

caught exception: type must be number, but is string

I am pretty new to C++11 and C++ exceptions, so sorry if the reason for this is obvious.

My platform/compiler is OSX 10.11.6 with AppleClang 8.0.0.8000042 and I tested this using json version 2.1.1.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions