Start JSON exception handling

This commit is contained in:
2025-06-24 13:43:03 -04:00
parent ddaf153340
commit 324ca06cf9
2 changed files with 65 additions and 1 deletions

View File

@@ -1,7 +1,69 @@
#pragma once #pragma once
#include <exception>
#include <sstream>
#include <format>
namespace json namespace json
{ {
class Exception : public std::exception {
private:
std::string whatstr;
public:
Exception(std::string base, std::string source, int index) {
//std::ostringstream s;
int counter = 0;
int line = 1;
int column = 0;
std::string lastline = "";
std::string whitespace = "";
for (auto c: source) {
if (counter == index) {
break;
}
if (c == '\n') {
line++;
column = 0;
lastline = "";
whitespace = "";
} else if (c == '\t') {
column++;
lastline += " ";
whitespace += " ";
} else {
column++;
lastline += c;
whitespace += " ";
}
counter++;
}
while (counter < source.size()) {
auto c = source[counter];
if (c == '\n') {
break;
}
lastline += c;
counter++;
}
// TODO: Migrate the below code bits to std::format
/*
s << base << " at line " << line << ", column " << column << std::endl;
s << lastline << std::endl;
s << whitespace << "^";*/
whatstr = std::format("{} at line {}, column {}\n{}\n{}^",
base, line, column,
lastline,
whitespace);
};
virtual const char* what() const throw() {
return whatstr.c_str();
}
};
class file_error : public std::runtime_error class file_error : public std::runtime_error
{ {

View File

@@ -2,6 +2,7 @@
#include <json.hpp> #include <json.hpp>
#include <tuple> #include <tuple>
#include <vector> #include <vector>
#include <error_handling.hpp>
namespace json { namespace json {
int lexers::lex_whitespace(std::string raw_json, int index) int lexers::lex_whitespace(std::string raw_json, int index)
@@ -43,7 +44,8 @@ namespace json {
// TODO: handle nested quotes // TODO: handle nested quotes
while (c = raw_json[index], c != '"') { while (c = raw_json[index], c != '"') {
if (index == raw_json.length()) { if (index == raw_json.length()) {
return {token, index, format_error("Unexpected EOF while lexing string", raw_json, index)}; //return {token, index, format_error("Unexpected EOF while lexing string", raw_json, index)};
throw Exception("Unexpected EOF while lexing string", raw_json, index);
} }
token.value += c; token.value += c;