JavaScript and TypeScript course ยท Module 5: Advanced JavaScript

Custom Error Classes

13 min read ยท
In this lesson8

Welcome back to Jurassic Park! In previous exercises we learned about the different kinds of errors in JavaScript and the basics of handling them with try...catch...finally. Now we'll dive deeper into creating custom, non-standard error classes, which are invaluable in large applications - like systems for managing a park full of prehistoric reptiles.

Why Custom Error Classes?

In complex systems like Jurassic Park, we need precise problem categorization. It's not enough to know "something went wrong" - we need to know exactly what happened, where, and how to react.

Custom error classes allow:

  1. Precisely categorizing different types of problems
  2. Attaching additional contextual data to errors
  3. Implementing custom helper methods
  4. Easier filtering and handling of specific cases

It's like the difference between a general park alarm and a precise message: "Velociraptors escaped from enclosure B6, last seen heading toward the visitor center."

Creating a Custom Error Hierarchy

For Jurassic Park we'll create a complete error hierarchy that reflects the domain:

// Base error class for all park problems
class JurassicParkError extends Error {
  constructor(message, code, severity = "medium") {
    super(message);
    this.name = "JurassicParkError";
    this.code = code;
    this.severity = severity;
    this.timestamp = new Date().toISOString();

    // Preserve the stack trace
    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, this.constructor);
    }
  }

  toJSON() {
    return {
      name: this.name,
      message: this.message,
      code: this.code,
      severity: this.severity,
      timestamp: this.timestamp,
      stack: this.stack
    };
  }

  toString() {
    return `[${this.severity.toUpperCase()}] ${this.name} (${this.code}): ${this.message}`;
  }
}

// Dinosaur-related errors
class DinosaurError extends JurassicParkError {
  constructor(message, code, dinosaurId, species, severity = "high") {
    super(message, code, severity);
    this.name = "DinosaurError";
    this.dinosaurId = dinosaurId;
    this.species = species;
  }
}

class DinosaurHealthError extends DinosaurError {
  constructor(dinosaurId, species, healthIssue, vitalSigns) {
    super(
      `Health issue with ${species} (ID: ${dinosaurId}): ${healthIssue}`,
      "DINO_HEALTH_ISSUE",
      dinosaurId,
      species,
      "medium"
    );
    this.name = "DinosaurHealthError";
    this.healthIssue = healthIssue;
    this.vitalSigns = vitalSigns;
  }
}

class DinosaurEscapeError extends DinosaurError {
  constructor(dinosaurId, species, lastKnownLocation) {
    super(
      `${species} (ID: ${dinosaurId}) has escaped! Last known location: ${lastKnownLocation}`,
      "DINO_ESCAPE",
      dinosaurId,
      species,
      "critical"
    );
    this.name = "DinosaurEscapeError";
    this.lastKnownLocation = lastKnownLocation;
  }
}

// Infrastructure errors
class ParkInfrastructureError extends JurassicParkError {
  constructor(message, code, system, severity = "high") {
    super(message, code, severity);
    this.name = "ParkInfrastructureError";
    this.system = system;
  }
}

class PowerSystemError extends ParkInfrastructureError {
  constructor(sector, powerLevel, backupAvailable) {
    super(
      `Power failure in sector ${sector}. Level: ${powerLevel}%. Backup: ${backupAvailable ? 'available' : 'unavailable'}`,
      "POWER_FAILURE",
      "power",
      backupAvailable ? "medium" : "critical"
    );
    this.name = "PowerSystemError";
    this.sector = sector;
    this.powerLevel = powerLevel;
    this.backupAvailable = backupAvailable;
  }
}

class FenceSystemError extends ParkInfrastructureError {
  constructor(sector, fenceId, integrity) {
    super(
      `Fence failure in sector ${sector}: ${fenceId}, integrity: ${integrity}%`,
      "FENCE_FAILURE",
      "fence",
      integrity < 50 ? "critical" : "high"
    );
    this.name = "FenceSystemError";
    this.sector = sector;
    this.fenceId = fenceId;
    this.integrity = integrity;
  }
}

Using the Error Hierarchy

// Incident management system
class IncidentManagementSystem {
  constructor() {
    this.incidents = [];
    this.alertLevel = "green";
  }

  reportIncident(error) {
    const incident = {
      id: `INC-${Date.now()}`,
      error: error.toJSON(),
      status: "open",
      reportedAt: new Date().toISOString(),
      actions: []
    };

    this.incidents.push(incident);
    this._updateAlertLevel(error);
    this._dispatchResponse(error, incident.id);

    return incident.id;
  }

  _updateAlertLevel(error) {
    const severityOrder = { low: 0, medium: 1, high: 2, critical: 3 };
    const currentLevel = this.alertLevel;

    if (error.severity === "critical") {
      this.alertLevel = "red";
    } else if (error.severity === "high" && currentLevel !== "red") {
      this.alertLevel = "orange";
    } else if (error.severity === "medium" && !["red", "orange"].includes(currentLevel)) {
      this.alertLevel = "yellow";
    }

    if (this.alertLevel !== currentLevel) {
      console.log(`Alert level changed: ${currentLevel} โ†’ ${this.alertLevel}`);
    }
  }

  _dispatchResponse(error, incidentId) {
    if (error instanceof DinosaurEscapeError) {
      console.log(`CRITICAL: Activating emergency protocol for ${error.species} escape!`);
      console.log(`Last known location: ${error.lastKnownLocation}`);
      // Activate lockdown, notify security teams, etc.
    } else if (error instanceof PowerSystemError) {
      console.log(`Power failure in sector ${error.sector}`);
      if (!error.backupAvailable) {
        console.log("CRITICAL: No backup power! Fences may be inactive!");
      }
    } else if (error instanceof FenceSystemError) {
      console.log(`Fence failure: sector ${error.sector}, integrity ${error.integrity}%`);
      if (error.integrity < 50) {
        console.log("CRITICAL: Fence integrity critical - potential breach risk!");
      }
    } else if (error instanceof DinosaurHealthError) {
      console.log(`Health alert for ${error.species}: ${error.healthIssue}`);
    } else {
      console.log(`General incident reported: ${error.message}`);
    }
  }

  getIncidentById(id) {
    return this.incidents.find(i => i.id === id);
  }

  resolveIncident(id, resolution) {
    const incident = this.getIncidentById(id);
    if (incident) {
      incident.status = "resolved";
      incident.resolvedAt = new Date().toISOString();
      incident.resolution = resolution;
    }
    return incident;
  }
}

// Example usage
const incidentSystem = new IncidentManagementSystem();

// Simulate a dinosaur escape
try {
  const fenceIntegrity = 20; // 20% - very low!
  if (fenceIntegrity < 30) {
    throw new FenceSystemError("B6", "FENCE-B6-NORTH", fenceIntegrity);
  }
} catch (error) {
  const incidentId = incidentSystem.reportIncident(error);
  console.log(`Incident recorded: ${incidentId}`);
  console.log(error.toString());
}

// Simulate a dinosaur health issue
try {
  const vitalSigns = { heartRate: 180, temperature: 41.5, respiratory: 45 };
  if (vitalSigns.temperature > 41) {
    throw new DinosaurHealthError("VEL-02", "Velociraptor", "High fever", vitalSigns);
  }
} catch (error) {
  const incidentId = incidentSystem.reportIncident(error);
  console.log(`Health incident: ${incidentId}`);
}

Error Serialization

One of the problems with error objects in JavaScript is their serialization. By default, when we try to convert an error to JSON, we lose most of the information:

const error = new Error('Test error');
console.log(JSON.stringify(error)); // {} - empty object!

Custom error classes can solve this problem by implementing a toJSON method:

class SerializableError extends Error {
  constructor(message) {
    super(message);
    this.name = this.constructor.name;
  }

  toJSON() {
    return {
      name: this.name,
      message: this.message,
      stack: this.stack,
      // Additional properties specific to subclasses
      ...Object.getOwnPropertyNames(this)
        .filter(prop => !['name', 'message', 'stack'].includes(prop))
        .reduce((obj, prop) => {
          obj[prop] = this[prop];
          return obj;
        }, {})
    };
  }
}

// Now we can create serializable errors
class DinosaurEscapeError extends SerializableError {
  constructor(message, species, location) {
    super(message);
    this.species = species;
    this.location = location;
    this.timestamp = new Date();
  }
}

const error = new DinosaurEscapeError(
  'Dinosaur escaped from enclosure',
  'Velociraptor',
  'Sector B6'
);

// Now the error can be properly serialized
console.log(JSON.stringify(error, null, 2));
/* Output:
{
  "name": "DinosaurEscapeError",
  "message": "Dinosaur escaped from enclosure",
  "stack": "DinosaurEscapeError: Dinosaur escaped from enclosure\n    at ...",
  "species": "Velociraptor",
  "location": "Sector B6",
  "timestamp": "2023-05-15T10:30:45.123Z"
}
*/

This is especially useful when we need to send error information through an API or save it in logs.

Handling Asynchronous Errors with Custom Classes

Custom error classes work great with asynchronous code:

// API-specific error class
class APIError extends Error {
  constructor(message, statusCode, endpoint) {
    super(message);
    this.name = 'APIError';
    this.statusCode = statusCode;
    this.endpoint = endpoint;
    this.timestamp = new Date();
  }

  isServerError() {
    return this.statusCode >= 500;
  }

  isClientError() {
    return this.statusCode >= 400 && this.statusCode < 500;
  }

  isAuthError() {
    return this.statusCode === 401 || this.statusCode === 403;
  }
}

// Function fetching data from API that uses a custom error class
async function fetchDinosaurData(dinoId) {
  try {
    const response = await fetch(`https://jurassic-park-api.com/dinosaurs/${dinoId}`);

    if (!response.ok) {
      throw new APIError(
        `Error fetching data for dinosaur #${dinoId}`,
        response.status,
        `/dinosaurs/${dinoId}`
      );
    }

    return await response.json();
  } catch (error) {
    if (error instanceof APIError) {
      // Handle API errors
      if (error.isAuthError()) {
        await refreshAuthToken();
        return fetchDinosaurData(dinoId); // Retry after refreshing the token
      } else if (error.isServerError()) {
        console.error('Server error, trying backup API...');
        return fetchDinosaurDataFromBackupAPI(dinoId);
      } else {
        console.error(`Client error: ${error.message} (statusCode: ${error.statusCode})`);
        throw error; // Re-throw the error
      }
    } else {
      // Other type of error (e.g., network error)
      console.error('Unexpected error:', error);
      throw new Error(`Failed to fetch dinosaur #${dinoId} data: ${error.message}`);
    }
  }
}

Advanced Example: Incident Reporting System

Let's see how we can use custom error classes in a more elaborate example - an incident reporting system for Jurassic Park:

// Base error class for incidents
class IncidentError extends Error {
  constructor(message, location, severity) {
    super(message);
    this.name = 'IncidentError';
    this.location = location;
    this.severity = severity; // 1-10
    this.timestamp = new Date();
    this.resolved = false;
    this.resolutionTime = null;
  }

  markAsResolved() {
    this.resolved = true;
    this.resolutionTime = new Date();
    return this;
  }

  getIncidentDuration() {
    if (!this.resolved) return null;
    return (this.resolutionTime - this.timestamp) / 1000; // in seconds
  }

  requiresEvacuation() {
    return this.severity >= 7;
  }

  requiresNotification() {
    return this.severity >= 4;
  }

  getSummary() {
    return {
      type: this.name,
      message: this.message,
      location: this.location,
      severity: this.severity,
      timestamp: this.timestamp,
      status: this.resolved ? 'Resolved' : 'Active',
      resolutionTime: this.resolutionTime
    };
  }

  toJSON() {
    return this.getSummary();
  }
}

// Classes for different incident types
class DinosaurEscapeIncident extends IncidentError {
  constructor(message, location, species, count, dangerLevel) {
    super(message, location, dangerLevel);
    this.name = 'DinosaurEscapeIncident';
    this.species = species;
    this.count = count;
    this.lastSighting = location;
  }

  updateSighting(newLocation) {
    this.lastSighting = newLocation;
    return this;
  }

  getSummary() {
    return {
      ...super.getSummary(),
      species: this.species,
      count: this.count,
      lastSighting: this.lastSighting
    };
  }
}

class SystemFailureIncident extends IncidentError {
  constructor(message, location, system, affectedAreas, backupStatus) {
    // Calculate criticality level based on system and backup availability
    const severity = SystemFailureIncident.calculateSeverity(system, backupStatus);

    super(message, location, severity);
    this.name = 'SystemFailureIncident';
    this.system = system;
    this.affectedAreas = affectedAreas;
    this.backupStatus = backupStatus;
  }

  static calculateSeverity(system, backupStatus) {
    const systemCriticality = {
      'electric_fences': 10,
      'security_doors': 9,
      'surveillance': 7,
      'climate_control': 6,
      'guest_services': 3
    };

    // If backup works, reduce criticality level
    const baseSeverity = systemCriticality[system] || 5;
    return backupStatus === 'operational' ? Math.max(3, baseSeverity - 3) : baseSeverity;
  }

  requiresMaintenanceTeam() {
    return true;
  }

  requiresEmergencyPower() {
    return this.system === 'electric_fences' || this.system === 'security_doors';
  }

  getSummary() {
    return {
      ...super.getSummary(),
      system: this.system,
      affectedAreas: this.affectedAreas,
      backupStatus: this.backupStatus,
      requiresEmergencyPower: this.requiresEmergencyPower()
    };
  }
}

class VisitorIncident extends IncidentError {
  constructor(message, location, visitorCount, injuryLevel, medicalStatus) {
    // Calculate criticality level based on visitor count and injury level
    const severity = VisitorIncident.calculateSeverity(visitorCount, injuryLevel);

    super(message, location, severity);
    this.name = 'VisitorIncident';
    this.visitorCount = visitorCount;
    this.injuryLevel = injuryLevel; // 'none', 'minor', 'moderate', 'severe'
    this.medicalStatus = medicalStatus; // 'not_required', 'dispatched', 'on_scene', 'evacuating'
  }

  static calculateSeverity(visitorCount, injuryLevel) {
    const injurySeverity = {
      'none': 1,
      'minor': 3,
      'moderate': 6,
      'severe': 9
    };

    // Increase criticality level for larger visitor groups
    const baseSeverity = injurySeverity[injuryLevel] || 5;
    const visitorFactor = visitorCount > 10 ? 2 : visitorCount > 3 ? 1 : 0;

    return Math.min(10, baseSeverity + visitorFactor);
  }

  requiresMedicalTeam() {
    return this.injuryLevel !== 'none';
  }

  updateMedicalStatus(newStatus) {
    this.medicalStatus = newStatus;

    // If medical help is on scene and situation is not critical,
    // we can reduce the criticality level
    if (newStatus === 'on_scene' && this.injuryLevel !== 'severe') {
      this.severity = Math.max(2, this.severity - 2);
    }

    return this;
  }

  getSummary() {
    return {
      ...super.getSummary(),
      visitorCount: this.visitorCount,
      injuryLevel: this.injuryLevel,
      medicalStatus: this.medicalStatus,
      requiresMedicalTeam: this.requiresMedicalTeam()
    };
  }
}

// Incident management system
class IncidentManagementSystem {
  constructor() {
    this.activeIncidents = new Map();
    this.resolvedIncidents = [];
    this.eventListeners = {
      'new': [],
      'update': [],
      'resolve': []
    };
  }

  reportIncident(incident) {
    if (!(incident instanceof IncidentError)) {
      throw new TypeError('Only IncidentError objects can be reported');
    }

    const incidentId = `INC-${Date.now()}-${Math.floor(Math.random() * 1000)}`;
    this.activeIncidents.set(incidentId, incident);

    // Notify all listeners about the new incident
    this._notifyListeners('new', { id: incidentId, incident });

    // Trigger automated responses
    this._triggerAutomatedResponses(incidentId, incident);

    return incidentId;
  }

  updateIncident(incidentId, updateFn) {
    if (!this.activeIncidents.has(incidentId)) {
      throw new Error(`Incident with ID ${incidentId} does not exist or has already been resolved`);
    }

    const incident = this.activeIncidents.get(incidentId);
    updateFn(incident);

    // Notify all listeners about the incident update
    this._notifyListeners('update', { id: incidentId, incident });

    return incident;
  }

  resolveIncident(incidentId, resolutionNotes = '') {
    if (!this.activeIncidents.has(incidentId)) {
      throw new Error(`Incident with ID ${incidentId} does not exist or has already been resolved`);
    }

    const incident = this.activeIncidents.get(incidentId);
    incident.markAsResolved();
    incident.resolutionNotes = resolutionNotes;

    // Move incident from active to resolved
    this.activeIncidents.delete(incidentId);
    this.resolvedIncidents.push({ id: incidentId, incident });

    // Notify all listeners about the resolution
    this._notifyListeners('resolve', { id: incidentId, incident });

    return incident;
  }

  getActiveIncidents() {
    return Array.from(this.activeIncidents.entries()).map(([id, incident]) => ({
      id,
      ...incident.getSummary()
    }));
  }

  addEventListener(event, callback) {
    if (!this.eventListeners[event]) {
      throw new Error(`Unknown event type: ${event}`);
    }

    this.eventListeners[event].push(callback);
    return () => this.removeEventListener(event, callback);
  }

  removeEventListener(event, callback) {
    if (!this.eventListeners[event]) return false;

    const index = this.eventListeners[event].indexOf(callback);
    if (index !== -1) {
      this.eventListeners[event].splice(index, 1);
      return true;
    }
    return false;
  }

  _notifyListeners(event, data) {
    if (!this.eventListeners[event]) return;

    for (const listener of this.eventListeners[event]) {
      try {
        listener(data);
      } catch (error) {
        console.error(`Error in ${event} event listener:`, error);
      }
    }
  }

  _triggerAutomatedResponses(incidentId, incident) {
    console.log(`Automated response for incident ${incidentId}:`, incident.name);

    // Different reactions depending on incident type
    if (incident instanceof DinosaurEscapeIncident) {
      if (incident.requiresEvacuation()) {
        console.log(`EVACUATION! Activating evacuation protocol for: ${incident.location}`);
      }

      console.log(`Dispatching ACU (Asset Containment Unit) to location: ${incident.lastSighting}`);
    }

    else if (incident instanceof SystemFailureIncident) {
      console.log(`Notifying maintenance team about system failure: ${incident.system}`);

      if (incident.requiresEmergencyPower()) {
        console.log('Activating emergency power system!');
      }
    }

    else if (incident instanceof VisitorIncident) {
      if (incident.requiresMedicalTeam()) {
        console.log(`Dispatching medical team to location: ${incident.location}`);

        // Update medical status
        this.updateIncident(incidentId, inc => inc.updateMedicalStatus('dispatched'));
      }

      if (incident.requiresEvacuation()) {
        console.log(`Starting visitor evacuation from: ${incident.location}`);
      }
    }

    // Common reactions for all incidents
    if (incident.requiresNotification()) {
      console.log('Notifying park management...');
    }
  }
}

// Example usage of the incident system
function demoParkIncidentSystem() {
  const incidentSystem = new IncidentManagementSystem();

  // Add listener for new incidents
  incidentSystem.addEventListener('new', ({ id, incident }) => {
    console.log(`NEW INCIDENT [${id}]: ${incident.name} at location ${incident.location}`);
  });

  // Report dinosaur incident
  const raptorIncidentId = incidentSystem.reportIncident(
    new DinosaurEscapeIncident(
      'Velociraptor escape from enclosure',
      'Sector C4',
      'Velociraptor',
      3,
      9 // High danger level
    )
  );

  // Update incident - change last sighting
  setTimeout(() => {
    incidentSystem.updateIncident(raptorIncidentId, incident => {
      incident.updateSighting('Sector C5 - near visitor center');
      console.log(`Update: Raptors spotted at ${incident.lastSighting}`);
    });
  }, 2000);

  // Report system incident
  const powerIncidentId = incidentSystem.reportIncident(
    new SystemFailureIncident(
      'Electric fence power failure',
      'Sector B1-B3',
      'electric_fences',
      ['TRex Paddock', 'Raptor Containment'],
      'offline' // Backup not working
    )
  );

  // Report visitor incident
  const visitorIncidentId = incidentSystem.reportIncident(
    new VisitorIncident(
      'Visitors outside designated tour route',
      'Sector D2',
      4, // Visitor count
      'minor', // Minor injuries
      'not_required' // Medical status
    )
  );

  // Display active incidents
  setTimeout(() => {
    console.log('\n--- ACTIVE INCIDENTS ---');
    console.table(incidentSystem.getActiveIncidents());
  }, 3000);

  // Resolve visitor incident
  setTimeout(() => {
    incidentSystem.resolveIncident(
      visitorIncidentId,
      'Visitors safely escorted back to the designated tour route.'
    );
    console.log(`Incident ${visitorIncidentId} marked as resolved.`);
  }, 4000);

  // Resolve power incident
  setTimeout(() => {
    incidentSystem.resolveIncident(
      powerIncidentId,
      'Power restored, fences active again.'
    );
    console.log(`Incident ${powerIncidentId} marked as resolved.`);
  }, 5000);

  // Resolve raptor incident
  setTimeout(() => {
    incidentSystem.resolveIncident(
      raptorIncidentId,
      'All 3 Velociraptors captured and safely transported back to enclosure.'
    );
    console.log(`Incident ${raptorIncidentId} marked as resolved.`);
  }, 6000);
}

// Run the demo
// demoParkIncidentSystem();

Best Practices for Creating Custom Error Classes

  1. Name errors meaningfully - the name should clearly indicate what went wrong
  2. Create an error hierarchy - use inheritance to create a logical error class hierarchy
  3. Add context - always attach additional information that will help diagnose and handle the error
  4. Implement helper methods - add methods that make error categorization and handling easier
  5. Ensure serializability - add a toJSON() method so errors can be easily logged and transmitted
  6. Preserve the stack trace - ensure you call super(message) in the constructor to preserve the stack trace
  7. Document your error classes - other developers (and future you) should know when and how to use your error classes

Conclusions

Custom error classes are a powerful tool in the JavaScript developer's arsenal. In complex applications like the Jurassic Park management system, precise categorization and handling of different error types is key to maintaining safety and stability.

Remember, as Dr. Ian Malcolm said: "Life... uh... finds a way." The same applies to errors in code. The best approach is not to pretend errors don't exist, but to expect them and be prepared to handle them in the most elegant and effective way possible.

In the next exercise we'll use all the techniques we've learned to implement a complete application demonstrating modules, asynchrony, and error handling in practice.

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. How do you properly create a custom error class in JavaScript?

  2. 2. What is the instanceof operator used for in error handling?

Hands-on tasks in the game

  • Code editor

    Implement ParkError, FenceBreachError, and PowerFailureError classes with helper methods.

  • Click in order

    Arrange the elements of a custom error class definition in the correct order:

  1. QuestionCreating a Custom Error Class
  2. QuestionThe instanceof Operator with Errors
  3. Coding taskPractice: Error Class Hierarchy
  4. Click in orderCustom Error Class Syntax

Useful articles