Files
json/include/error_handling.hpp
2025-06-24 13:43:03 -04:00

86 lines
2.1 KiB
C++

#pragma once
#include <exception>
#include <sstream>
#include <format>
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 io_error : public std::runtime_error
{
};
class parse_error : public std::runtime_error
{
};
class json_runtime_error : public std::runtime_error
{
};
}