jorgen / json_struct

json_struct is a single header only C++ library for parsing JSON directly to C++ structs and vice versa
Other
422 stars 57 forks source link

makeErrorString() fails with exception in basic_string::_M_create #14

Closed DraTeots closed 3 years ago

DraTeots commented 3 years ago
#include "json_struct.h"

struct AfterburnerConfig 
{
    double beam_hor_variance = 0;
    JS_OBJ(beam_hor_variance);
};

I put some invalid JSon here:

{
    /* dfd */
    "beam_hor_variance" : 6.0,
}

Readout code is nothing fancy:

// Read
{
    std::ifstream reader(file_name);
    std::stringstream buffer;
    buffer << reader.rdbuf();
    auto json = buffer.str();

    AfterburnerConfig config2;
    JS::ParseContext parseContext(json);
    if (parseContext.parseTo(config2) != JS::Error::NoError)
    {
        std::string errorStr = parseContext.makeErrorString();   // <=== fails here
        throw std::runtime_error(errorStr);
    }
    REQUIRE(config2.beam_hor_variance == Catch::Approx( 6 ));
}

Instead of getting an error with message about the wrong character it fails in makeErrorString():

due to unexpected exception with message:
  basic_string::_M_create

It fails exactly here:

inline std::string Tokenizer::makeErrorString() const
{
  static_assert(sizeof(Internal::error_strings) / sizeof *Internal::error_strings == size_t(Error::UserDefinedErrors),
                "Please add missing error message");

  std::string retString("Error");
  if (error_context.error < Error::UserDefinedErrors)
    retString += std::string(" ") + Internal::error_strings[int(error_context.error)];
  if (error_context.custom_message.size())
    retString += " " + error_context.custom_message;
  retString += std::string(":\n");
  for (size_t i = 0; i < error_context.lines.size(); i++)
  {
    retString += error_context.lines[i] + "\n";
    if (i == error_context.line)
    {
      std::string pointing(error_context.character + 1, ' ');
      pointing[error_context.character - 1] = '^';
      pointing[error_context.character] = '\n';
      retString += pointing;   // <========= HERE 
    }
  }
  return retString;
}
jorgen commented 3 years ago

Thank you for the excellent bug report! This is now fixed by 1229c3d0a28b1768c986fd951219e36e9cf1eb01. I'm sorry for the inconvenience this has caused you!

DraTeots commented 3 years ago

Thank you for excellent library and quick response!