JavaScript and TypeScript course ยท Module 5: Advanced JavaScript
Final Project: Jurassic Park Diagnostics System
In this lesson4
Welcome to the final exercise of Module 5! We're going to build a complete Jurassic Park Diagnostics System that applies everything we've learned: custom error classes, a professional logging system, nested try/catch blocks, the finally clause, and modular code architecture.
"We need a system that can scan all park subsystems and generate a comprehensive diagnostic report," says Dr. Ellie Sattler. "Fences, power, sensors - and when something goes wrong, the system must log it, classify it by severity, and recommend a response."
System Architecture
The diagnostics system consists of four modules:
- Custom error hierarchy - ParkError, FenceError, PowerError, SensorError, SecurityBreachError
- Logging system - ParkLogger with log levels (DEBUG, INFO, WARN, ERROR, FATAL)
- Diagnostic module - ParkDiagnostics scanning subsystems with nested try/catch/finally
- Reporting module - DiagnosticsReporter aggregating results and generating recommendations
1. Custom Error Hierarchy
// Base error for all park issues
class ParkError extends Error {
constructor(message, code, sector, severity = "medium") {
super(message);
this.name = "ParkError";
this.code = code;
this.sector = sector;
this.severity = severity;
this.timestamp = new Date().toISOString();
this.resolved = false;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
}
resolve() {
this.resolved = true;
this.resolvedAt = new Date().toISOString();
return this;
}
toReport() {
return {
name: this.name,
message: this.message,
code: this.code,
sector: this.sector,
severity: this.severity,
timestamp: this.timestamp,
resolved: this.resolved
};
}
}
// Fence error - physical security
class FenceError extends ParkError {
constructor(sector, fenceId, integrity) {
const severity = integrity < 50 ? "critical" : integrity < 70 ? "high" : "medium";
super(
`Fence failure ${fenceId} in sector ${sector}: integrity ${integrity}%`,
"FENCE_FAILURE",
sector,
severity
);
this.name = "FenceError";
this.fenceId = fenceId;
this.integrity = integrity;
}
}
// Power error - infrastructure
class PowerError extends ParkError {
constructor(sector, powerLevel, backupAvailable) {
const severity = !backupAvailable && powerLevel < 30 ? "critical" : "high";
super(
`Power failure in sector ${sector}: ${powerLevel}%. Backup: ${backupAvailable ? "available" : "unavailable"}`,
"POWER_FAILURE",
sector,
severity
);
this.name = "PowerError";
this.powerLevel = powerLevel;
this.backupAvailable = backupAvailable;
}
}
// Sensor error
class SensorError extends ParkError {
constructor(sector, sensorId, issue) {
super(
`Sensor ${sensorId} failure in sector ${sector}: ${issue}`,
"SENSOR_FAILURE",
sector,
"medium"
);
this.name = "SensorError";
this.sensorId = sensorId;
this.issue = issue;
}
}
// Security breach - always critical
class SecurityBreachError extends ParkError {
constructor(sector, breachType, speciesInvolved) {
super(
`SECURITY BREACH in ${sector}: ${breachType} - species: ${speciesInvolved}`,
"SECURITY_BREACH",
sector,
"critical"
);
this.name = "SecurityBreachError";
this.breachType = breachType;
this.speciesInvolved = speciesInvolved;
}
}Each error type carries additional contextual information, making diagnosis and repair easier.
2. Logging System (Logger with Levels)
The second module is a professional logging system that records all events with appropriate severity and context.
// Log levels
const LogLevel = {
DEBUG: 0,
INFO: 1,
WARN: 2,
ERROR: 3,
FATAL: 4
};
const LogLevelNames = ["DEBUG", "INFO", "WARN", "ERROR", "FATAL"];
class ParkLogger {
constructor(moduleName, minLevel = LogLevel.DEBUG) {
this.moduleName = moduleName;
this.minLevel = minLevel;
this.logs = [];
this.maxLogs = 1000; // Stored log limit
}
_log(level, message, context = {}) {
if (level < this.minLevel) return;
const entry = {
timestamp: new Date().toISOString(),
level: LogLevelNames[level],
module: this.moduleName,
message,
context
};
this.logs.push(entry);
// Log rotation - remove oldest
if (this.logs.length > this.maxLogs) {
this.logs = this.logs.slice(-this.maxLogs);
}
// Format output
const prefix = `[${entry.timestamp}] [${entry.level}] [${this.moduleName}]`;
const contextStr = Object.keys(context).length > 0
? ` | ${JSON.stringify(context)}`
: "";
switch (level) {
case LogLevel.DEBUG: console.log(`${prefix} ${message}${contextStr}`); break;
case LogLevel.INFO: console.info(`${prefix} ${message}${contextStr}`); break;
case LogLevel.WARN: console.warn(`${prefix} ${message}${contextStr}`); break;
case LogLevel.ERROR: console.error(`${prefix} ${message}${contextStr}`); break;
case LogLevel.FATAL: console.error(`${prefix} ${message}${contextStr}`); break;
}
return entry;
}
debug(message, context) { return this._log(LogLevel.DEBUG, message, context); }
info(message, context) { return this._log(LogLevel.INFO, message, context); }
warn(message, context) { return this._log(LogLevel.WARN, message, context); }
error(message, context) { return this._log(LogLevel.ERROR, message, context); }
fatal(message, context) { return this._log(LogLevel.FATAL, message, context); }
// Filter logs by level
getLogsByLevel(level) {
const levelName = LogLevelNames[level];
return this.logs.filter(log => log.level === levelName);
}
// Log statistics
getStats() {
const stats = { total: this.logs.length };
LogLevelNames.forEach(name => {
stats[name] = this.logs.filter(l => l.level === name).length;
});
return stats;
}
}The logger supports level filtering, stores event history, and automatically rotates old logs.
3. Diagnostic Module (Scanning and try/catch/finally)
The third module is the heart of the system - it scans individual park subsystems, catches and classifies errors, then takes appropriate corrective actions.
class ParkDiagnostics {
constructor() {
this.logger = new ParkLogger("Diagnostics", LogLevel.DEBUG);
this.errors = [];
this.scanResults = [];
}
// Simulate fence scanning
scanFence(sector, fenceId) {
this.logger.info(`Scanning fence ${fenceId} in sector ${sector}`);
try {
const integrity = Math.round(40 + Math.random() * 60);
if (integrity < 80) {
throw new FenceError(sector, fenceId, integrity);
}
this.logger.debug(`Fence ${fenceId} OK: ${integrity}%`, { sector, fenceId });
return { status: "OK", integrity };
} catch (error) {
if (error instanceof FenceError) {
this.errors.push(error);
this.logger.error(error.message, error.toReport());
if (error.severity === "critical") {
this.logger.fatal(`CRITICAL fence failure! Evacuate sector ${sector}!`);
this._initiateEmergencyProtocol(sector);
}
} else {
// Unexpected error - log and re-throw
this.logger.fatal(`Unexpected error during scan: ${error.message}`);
throw error;
}
return { status: "FAILURE", error: error.toReport() };
} finally {
this.logger.debug(`Fence ${fenceId} scan completed`);
}
}
// Power scanning with nested try/catch
scanPower(sector) {
this.logger.info(`Scanning power in sector ${sector}`);
try {
const mainPower = Math.round(Math.random() * 100);
let backupStatus = false;
try {
// Attempt to check backup power
backupStatus = Math.random() > 0.3;
if (!backupStatus && mainPower < 30) {
throw new PowerError(sector, mainPower, false);
}
} catch (innerError) {
if (innerError instanceof PowerError) {
this.errors.push(innerError);
this.logger.error(`Power issue: ${innerError.message}`);
} else {
throw innerError; // Pass unknown errors to outer catch
}
}
if (mainPower < 50) {
throw new PowerError(sector, mainPower, backupStatus);
}
return { status: "OK", mainPower, backupActive: backupStatus };
} catch (error) {
if (error instanceof PowerError) {
this.errors.push(error);
this.logger.warn(error.message, error.toReport());
return { status: "WARNING", error: error.toReport() };
}
throw error;
}
}
// Full sector diagnostics
runFullDiagnostics(sector) {
this.logger.info(`=== Full diagnostics for sector: ${sector} ===`);
const startTime = performance.now();
const result = {
sector,
fences: [],
power: null,
errors: [],
duration: 0
};
try {
// Scan fences (3 fences per sector)
for (let i = 1; i <= 3; i++) {
const fenceResult = this.scanFence(sector, `FENCE-${sector}-${i}`);
result.fences.push(fenceResult);
}
// Scan power
result.power = this.scanPower(sector);
} catch (unexpectedError) {
this.logger.fatal(`Unexpected diagnostics error: ${unexpectedError.message}`);
result.criticalFailure = true;
} finally {
result.duration = `${(performance.now() - startTime).toFixed(2)}ms`;
result.errors = this.errors.filter(e => e.sector === sector).map(e => e.toReport());
this.scanResults.push(result);
this.logger.info(`Diagnostics ${sector} completed in ${result.duration}`);
}
return result;
}
_initiateEmergencyProtocol(sector) {
this.logger.fatal(`EMERGENCY PROTOCOL for sector ${sector} - sending notifications`);
}
}Note the nested try/catch blocks and the use of finally to record operation duration regardless of outcome.
4. Reporting Module (Data Aggregation and Analysis)
The last module collects data from all diagnostics and generates a readable report with recommendations.
class DiagnosticsReporter {
constructor(diagnostics) {
this.diagnostics = diagnostics;
this.logger = new ParkLogger("Reporting", LogLevel.INFO);
}
generateReport() {
const allErrors = this.diagnostics.errors;
const scanResults = this.diagnostics.scanResults;
// Group errors by type
const errorsByType = {};
allErrors.forEach(error => {
const type = error.name;
if (!errorsByType[type]) errorsByType[type] = [];
errorsByType[type].push(error.toReport());
});
// Group errors by sector
const errorsBySector = {};
allErrors.forEach(error => {
if (!errorsBySector[error.sector]) errorsBySector[error.sector] = [];
errorsBySector[error.sector].push(error.toReport());
});
// Count by severity
const severityCounts = { low: 0, medium: 0, high: 0, critical: 0 };
allErrors.forEach(error => {
severityCounts[error.severity]++;
});
const report = {
generatedAt: new Date().toISOString(),
summary: {
totalErrors: allErrors.length,
criticalErrors: severityCounts.critical,
sectorsScanned: scanResults.length,
overallStatus: severityCounts.critical > 0 ? "CRITICAL" :
severityCounts.high > 0 ? "WARNING" : "STABLE"
},
errorsByType,
errorsBySector,
severityCounts,
recommendations: this._generateRecommendations(allErrors, severityCounts)
};
this._printReport(report);
return report;
}
_generateRecommendations(errors, severity) {
const recommendations = [];
if (severity.critical > 0) {
recommendations.push("IMMEDIATELY: Evacuate sectors with critical fence failures");
recommendations.push("Deploy repair teams to damaged fences");
}
if (severity.high > 0) {
recommendations.push("URGENT: Review fences with reduced integrity");
}
const fenceErrors = errors.filter(e => e instanceof FenceError);
if (fenceErrors.length > 3) {
recommendations.push("Systematic review of all fences - multiple failures detected");
}
const powerErrors = errors.filter(e => e instanceof PowerError);
if (powerErrors.length > 0) {
recommendations.push("Check backup generators in all sectors");
}
if (recommendations.length === 0) {
recommendations.push("All systems stable - continue standard monitoring");
}
return recommendations;
}
_printReport(report) {
console.log("\n" + "=".repeat(60));
console.log(" JURASSIC PARK DIAGNOSTIC REPORT");
console.log("=".repeat(60));
console.log(`Generated: ${report.generatedAt}`);
console.log(`Status: ${report.summary.overallStatus}`);
console.log(`Sectors scanned: ${report.summary.sectorsScanned}`);
console.log(`Errors detected: ${report.summary.totalErrors} (critical: ${report.summary.criticalErrors})`);
console.log("\nErrors by type:");
Object.entries(report.errorsByType).forEach(([type, errors]) => {
console.log(` ${type}: ${errors.length}`);
});
console.log("\nRecommendations:");
report.recommendations.forEach((rec, i) => {
console.log(` ${i + 1}. ${rec}`);
});
console.log("=".repeat(60));
}
}
// Run the diagnostic system
const diagnostics = new ParkDiagnostics();
const sectors = ["T-Rex-Paddock", "Raptor-Pen", "Herbivore-Valley"];
sectors.forEach(sector => diagnostics.runFullDiagnostics(sector));
const reporter = new DiagnosticsReporter(diagnostics);
reporter.generateReport();
// Logger statistics
console.log("\nLog statistics:", diagnostics.logger.getStats());Implementation Tips
When building the diagnostic system, keep these principles in mind:
The error hierarchy should reflect the domain:
// Each error type = one kind of park problem
ParkError // base - general park error
โโโ FenceError // fences - physical security
โโโ PowerError // power - infrastructure
โโโ SensorError // sensors - monitoring
โโโ SecurityBreachError // breaches - highest priorityUse instanceof to distinguish error types:
try {
riskyOperation();
} catch (error) {
if (error instanceof SecurityBreachError) {
// Immediate response
} else if (error instanceof FenceError) {
// Repair protocol
} else if (error instanceof ParkError) {
// General park error handling
} else {
// Unknown error - log and escalate
throw error;
}
}Always use finally for cleanup:
function scanWithCleanup() {
const connection = openConnection();
try {
return performScan(connection);
} catch (error) {
logError(error);
return null;
} finally {
// Always close the connection - even on error
connection.close();
}
}Good Luck!
This project is your chance to prove you can build resilient, well-organized systems. In Jurassic Park there's no room for unhandled exceptions - every error must be caught, logged, and handled before the situation gets out of control. As John Hammond said: "We spared no expense!" - and you shouldn't spare effort when it comes to error handling.
Create your diagnostic system in the editor below. Implement your own error types, logging system, and a diagnostic mechanism for at least two park subsystems.
Code for this lesson: index.js
// Final project: Jurassic Park diagnostics system
// Combine: modules, error handling, try/catch, custom errors
// === 1. ERROR HIERARCHY ===
// TODO: Create a class ParkError that extends Error
class ParkError extends Error {
constructor(message, code, sector, severity) {
super(message);
this.name = "ParkError";
// TODO: Assign code, sector, severity, timestamp
}
// TODO: A method toReport() that returns a report object
}
// TODO: Create the derived classes: FenceError, PowerError, SystemError
class FenceError extends ParkError {
constructor(message, sector, fenceId) {
// TODO: Call super with the right parameters
}
}
// === 2. LOGGING SYSTEM ===
// TODO: Create a Logger object with the levels: debug, info, warn, error
const Logger = {
logs: [],
// TODO: Methods log(level, message, context)
// TODO: Method getLogsByLevel(level)
// TODO: Method exportLogs()
};
// === 3. DIAGNOSTICS MODULE ===
// TODO: Create diagnostic functions that use try/catch/finally
function scanSubsystem(subsystemName) {
// TODO: Simulate scanning the subsystem
// TODO: Use try/catch to catch errors
// TODO: Use finally to log the end of the scan
}
// === 4. REPORT GENERATOR ===
// TODO: Create a function generateDiagnosticReport()
// Collect data from all subsystems
// Handle each subsystem's errors separately
function generateDiagnosticReport() {
console.log("=== DIAGNOSTIC REPORT ===");
const subsystems = ["Fences", "Power", "Monitoring", "Communication"];
// TODO: Scan each subsystem with error handling
console.log("=== END OF REPORT ===");
}
// Run the diagnostics:
generateDiagnosticReport();Docs entries used in this lesson
Spotted a mistake in this lesson?