-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest-bug.js
More file actions
77 lines (63 loc) · 2.02 KB
/
Copy pathtest-bug.js
File metadata and controls
77 lines (63 loc) · 2.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#!/usr/bin/env node
// test-bug.js — Simulates a real-world bug: a config parser that crashes
// when required fields are missing from a JSON config file.
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
function loadConfig(filePath) {
const raw = readFileSync(resolve(filePath), "utf8");
return JSON.parse(raw);
}
function validateConfig(config) {
const required = ["database", "server", "auth"];
const missing = [];
for (const key of required) {
if (!config[key]) {
missing.push(key);
}
}
if (missing.length > 0) {
throw new Error(
`Invalid config: missing required fields: ${missing.join(", ")}. ` +
`Expected at least: ${required.join(", ")}. ` +
`Got: ${Object.keys(config).join(", ") || "none"}`
);
}
return config;
}
function setupDatabase(dbConfig) {
if (!dbConfig.host || !dbConfig.port) {
throw new TypeError(
`Cannot connect to database: host and port are required. ` +
`Received host="${dbConfig.host}", port=${dbConfig.port}`
);
}
// Simulate connection attempt
const connection = { connected: false, host: dbConfig.host, port: dbConfig.port };
if (dbConfig.password === "wrong") {
connection.error = new Error(
`Authentication failed for user "${dbConfig.user}" on ${dbConfig.host}:${dbConfig.port}`
);
} else {
connection.connected = true;
}
return connection;
}
// --- Main ---
try {
const config = loadConfig("./test-config.json");
const validated = validateConfig(config);
const db = setupDatabase(validated.database);
if (!db.connected) {
throw db.error || new Error("Database connection failed for unknown reason");
}
console.log("Config loaded successfully:", JSON.stringify(validated, null, 2));
} catch (err) {
console.error("FATAL: Application startup failed");
console.error(`Error: ${err.message}`);
console.error(`Code: ${err.code || "ERR_APP_STARTUP"}`);
if (err.stack) {
console.error("Stack trace:");
console.error(err.stack);
}
process.exit(1);
}