bobfang1992 / pytomlpp

A python wrapper for tomlplusplus
https://bobfang1992.github.io/pytomlpp/pytomlpp.html
MIT License
86 stars 10 forks source link

Error handling discards source location #29

Closed marzer closed 4 years ago

marzer commented 4 years ago

When you're calling toml::parse you're only using the 'what' part of the error, and not the 'where': https://github.com/bobfang1992/pytomlpp/blob/2e59a9b5585298ea1da6b7fc35d2405d4b0624f1/src/pytomlpp.cpp#L7-L14 This will pass on something like:

Error while parsing key-value pair: cannot redefine existing string 'bar' as integer

If you want to pass on the full error information including where it happened, catch the exception as a toml::parse_error instead and use the source() member function to access it. Here's a basic example from toml++'s operator << operator for printing parse_errors out to streams:

    template <typename Char>
    TOML_EXTERNAL_LINKAGE
    std::basic_ostream<Char>& operator << (std::basic_ostream<Char>& lhs, const parse_error& rhs)
    {
        lhs << rhs.description(); // same as what()
        lhs << "\n\t(error occurred at "sv;
        lhs << rhs.source();
        lhs << ")"sv;
        return lhs;
    }

Which, given the same input as the example above, will generate the following:

Error while parsing key-value pair: cannot redefine existing string 'bar' as integer
        (error occurred at line 3, column 8)

Your users will likely find having the line information very useful in these situations!

If the built-in error message formatting meets your needs you can just use a stringstream to stringify the toml::parse_error and use that as the input to the pytomlpp::DecodeError constructor, though my suggestion would be to expose the source information python-side as well in the event people wish to make use of it in their own error-handling schemes.

Relevant docs:

bobfang1992 commented 4 years ago

Thanks for the post! Yeah, I thought about this when I was implementing it. I agree this would be very useful. I will add it to the TODO list.

bobfang1992 commented 4 years ago

Added this. I have done a bit testing and it seems that although I added members to the python exception class on the python side these members are not exposed directly. I might need to dig further into that but for now, the basic functionality of having the line/column information in the error message has been added.