Skip to content

Commit bd273f4

Browse files
committed
add file opening closing try catch
1 parent 18efda8 commit bd273f4

File tree

2 files changed

+33
-13
lines changed

2 files changed

+33
-13
lines changed

src/object.cpp

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -184,15 +184,26 @@ void json::object::reset() {
184184
}
185185
void json::object::dump(std::string filename, size_t indent) const {
186186
std::ofstream file;
187-
file.open(filename);
188-
if (!file.is_open()) {
187+
188+
try {
189+
file.open(filename);
190+
if (!file.is_open()) {
191+
logger::error(
192+
"Failed to open file " + filename,
193+
"void json::object::dump(std::string filename, size_t indent)");
194+
}
195+
196+
file << this->dumps(indent);
197+
file.close();
198+
} catch (const std::exception &e) {
189199
logger::error(
190-
"Failed to open file " + filename,
200+
"Error encountered for: " + filename + " - " + std::string(e.what()),
201+
"void json::object::dump(std::string filename, size_t indent)");
202+
} catch (...) {
203+
logger::error(
204+
"An unknown error occurred for file: " + filename,
191205
"void json::object::dump(std::string filename, size_t indent)");
192206
}
193-
194-
file << this->dumps(indent);
195-
file.close();
196207
return;
197208
}
198209
std::string json::object::dumps(size_t indent, size_t baseIndent) const {

src/parse.cpp

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,14 +7,23 @@ json::parser::parser(std::string data) : input(data) { return; }
77
json::parser::~parser() { return; }
88

99
json::object json::parser::load(std::string path) {
10-
std::ifstream file(path);
11-
if (!file.is_open())
12-
logger::error("File not found " + path,
13-
"json::object json::parser::load(std::string path)");
14-
1510
std::stringstream buffer;
16-
buffer << file.rdbuf();
17-
file.close();
11+
12+
try {
13+
std::ifstream file(path);
14+
if (!file.is_open())
15+
logger::error("File not found " + path,
16+
"json::object json::parser::load(std::string path)");
17+
18+
buffer << file.rdbuf();
19+
file.close();
20+
} catch (std::exception &e) {
21+
logger::error("Error reading file: " + path + " - " + e.what(),
22+
"json::object json::parser::load(std::string path)");
23+
} catch (...) {
24+
logger::error("Error reading file " + path,
25+
"json::object json::parser::load(std::string path)");
26+
}
1827

1928
return this->loads(buffer.str());
2029
}

0 commit comments

Comments
 (0)