JavaScript and TypeScript course · Module 4: Asynchronous JavaScript
Error Handling (try...catch)
In this lesson8
In managing Jurassic Park, where dinosaurs can escape from enclosures, security systems can fail, and visitors can find themselves in danger, proper error handling is critically important. In JavaScript, just as in park safety procedures, we must be prepared for unexpected situations and know how to respond to them.
In this exercise we will focus on error handling strategies in asynchronous code, which is essential for building resilient and reliable applications.
Why Is Error Handling Important?
Imagine you are building a dinosaur enclosure monitoring system. What happens if a temperature sensor stops working? Or if the connection to the security system is interrupted? Without proper error handling, your application may "freeze" or, worse, continue operating based on incorrect data.
Good error handling:
- Prevents "cascading failures" - one error should not bring down the entire system
- Provides useful diagnostic information - helps quickly identify and fix problems
- Enables corrective actions - automatic retries, switching to backup systems
- Ensures graceful degradation - even when some features are unavailable, critical systems continue to work
Types of JavaScript Errors
Before diving into error handling strategies, let's discuss the different types of errors you can encounter in JavaScript:
1. Syntax Errors (SyntaxError)
Occur when code contains invalid syntax. They are detected during compilation and prevent the code from running.
// Example of a syntax error
function fetchDinosaurData( { // Missing closing parenthesis
// function body
}2. Reference Errors (ReferenceError)
Occur when we try to access a variable or function that does not exist.
// Example of a reference error
function updateDinosaurStatus(id) {
// The variable 'statuses' has not been defined
statuses[id] = "Active";
}3. Type Errors (TypeError)
Occur when an operation is performed on a value of the wrong type.
// Example of a type error
function countDinosaurs(dinosaurList) {
// If dinosaurList is not an array, a TypeError will occur
return dinosaurList.length;
}4. Range Errors (RangeError)
Occur when a numeric value or parameter is outside the allowable range.
// Example of a range error
function setEnclosureTemperature(temperature) {
// If temperature is too high, a RangeError is thrown
if (temperature > 50) {
throw new RangeError("Enclosure temperature cannot exceed 50°C");
}
// rest of code
}5. URI Errors (URIError)
Occur in case of improper use of URI encoding/decoding functions.
// Example of a URI error
try {
// Attempt to decode an invalid URI
decodeURIComponent('%');
} catch (error) {
console.error("Invalid URI:", error.message);
}6. EvalError
Occurred historically for errors related to the eval() function, though rarely seen in modern JavaScript.
7. Custom Errors
We can create and throw our own errors to handle application-specific cases.
// Example of a custom error
class DinosaurEscapeError extends Error {
constructor(dinoId, paddockId, message) {
super(message || `Dinosaur #${dinoId} escaped from paddock #${paddockId}!`);
this.name = "DinosaurEscapeError";
this.dinoId = dinoId;
this.paddockId = paddockId;
this.timestamp = new Date();
}
}
// Usage
function checkPaddockStatus(paddockId) {
const status = fetchPaddockStatus(paddockId);
if (status.dinosaur && !status.gatesClosed) {
throw new DinosaurEscapeError(
status.dinosaur.id,
paddockId,
`ALERT! Dinosaur ${status.dinosaur.name} escaped from paddock #${paddockId}!`
);
}
return status;
}Basic Error Handling with try...catch
The fundamental error handling mechanism in JavaScript is the try...catch block:
try {
// Code that might throw an error
const paddockStatus = checkPaddockStatus(12);
updateMonitoringPanel(paddockStatus);
} catch (error) {
// Error handling code
console.error("Paddock check error:", error.message);
activateAlarm("Paddock monitoring error", error);
} finally {
// This code always runs, regardless of whether an error occurred
writeSystemLog("Finished checking paddock 12");
}In the example above:
- The
tryblock contains code that might throw an error - The
catchblock executes when an error occurs in thetryblock - The
finallyblock always executes, regardless of whether an error occurred or not
Error Object Properties
The error object passed to the catch block contains many useful properties:
try {
throw new Error("Something went wrong");
} catch (error) {
console.error("Error name:", error.name); // "Error"
console.error("Message:", error.message); // "Something went wrong"
console.error("Stack trace:", error.stack); // Stack trace showing where the error occurred
}Checking Error Type
We often want to react differently to different types of errors:
try {
const result = performRiskyOperation();
displayResult(result);
} catch (error) {
if (error instanceof SyntaxError) {
console.error("Syntax error:", error.message);
} else if (error instanceof ReferenceError) {
console.error("Reference error:", error.message);
} else if (error instanceof DinosaurEscapeError) {
// Trigger emergency procedure!
activateSecurityProtocol(error.dinoId, error.paddockId);
evacuateVisitors();
notifySecurityTeam(error);
} else {
console.error("Unknown error occurred:", error);
}
}Throwing Errors (throw)
We can throw errors ourselves using the throw keyword:
function setEnclosureTemperature(enclosureId, temperature) {
// Validate arguments
if (typeof enclosureId !== 'number' || enclosureId <= 0) {
throw new TypeError("Enclosure ID must be a positive number");
}
if (temperature < 10 || temperature > 40) {
throw new RangeError("Temperature must be between 10°C and 40°C");
}
// Rest of code that will set the temperature
return updateEnclosureTemperature(enclosureId, temperature);
}
// Usage
try {
setEnclosureTemperature("invalid-id", 25);
} catch (error) {
if (error instanceof TypeError) {
console.error("Invalid argument type:", error.message);
} else if (error instanceof RangeError) {
console.error("Value out of range:", error.message);
} else {
console.error("Unexpected error:", error.message);
}
}Creating Custom Error Classes
For more advanced error handling, we can create custom error classes that inherit from Error:
// Error hierarchy for park systems
class ParkError extends Error {
constructor(message) {
super(message);
this.name = this.constructor.name;
// Preserve stack trace
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
}
}
class SecuritySystemError extends ParkError {
constructor(message, systemId) {
super(message || `Security system error #${systemId}`);
this.systemId = systemId;
}
}
class FeedingSystemError extends ParkError {
constructor(message, paddockId, foodType) {
super(message || `Feeding system error in paddock #${paddockId}`);
this.paddockId = paddockId;
this.foodType = foodType;
}
}
class VisitorSystemError extends ParkError {
constructor(message, areaId, visitorCount) {
super(message || `Visitor system error in area #${areaId}`);
this.areaId = areaId;
this.visitorCount = visitorCount;
}
}
// Usage
function startFeedingSystem(paddockId, foodType) {
try {
if (!paddockExists(paddockId)) {
throw new FeedingSystemError(
`Cannot start feeding system: Paddock #${paddockId} does not exist`,
paddockId,
foodType
);
}
// More code...
} catch (error) {
if (error instanceof FeedingSystemError) {
// Handle feeding system error specifically
notifyFeedingStaff(error);
return { success: false, error: error.message, systemType: "feeding" };
} else {
console.error("Unexpected error:", error);
return { success: false, error: "Unknown system error", systemType: "unknown" };
}
}
}Error Handling in Asynchronous Code
Error handling in asynchronous code can be more complex, especially when dealing with callbacks, Promises, and async/await functions.
Error Handling in Callbacks
In older async programming styles using callbacks, the "error-first" pattern was common:
// Error-first style
function fetchDinosaurData(id, callback) {
setTimeout(() => {
if (id <= 0) {
// First argument is the error (if any)
callback(new Error(`Invalid dinosaur ID: ${id}`), null);
} else {
// First argument is null (no error), second is the result
callback(null, { id, name: `Dino-${id}`, species: "Tyrannosaurus" });
}
}, 1000);
}
// Usage
fetchDinosaurData(0, (error, dino) => {
if (error) {
console.error("Failed to fetch dinosaur data:", error.message);
return;
}
console.log("Fetched dinosaur data:", dino);
});Error Handling in Promises
In Promises we use the .catch() method to handle errors:
function fetchDinosaurData(id) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (id <= 0) {
reject(new Error(`Invalid dinosaur ID: ${id}`));
} else {
resolve({ id, name: `Dino-${id}`, species: "Tyrannosaurus" });
}
}, 1000);
});
}
// Usage
fetchDinosaurData(0)
.then(dino => {
console.log("Fetched dinosaur data:", dino);
})
.catch(error => {
console.error("Failed to fetch dinosaur data:", error.message);
});Promises allow chained error handling:
fetchDinosaurData(42)
.then(dino => {
return updateDinosaurStatus(dino.id, "active");
})
.then(status => {
console.log("Status updated:", status);
return sendNotification("Dinosaur activated");
})
.catch(error => {
// This catch handles errors from all preceding operations
console.error("Error occurred in operation chain:", error.message);
});Error Handling with async/await
Async/await functions allow using traditional try...catch syntax even for asynchronous code:
async function activateDinosaur(id) {
try {
console.log(`Starting activation procedure for dinosaur #${id}...`);
const dino = await fetchDinosaurData(id);
console.log(`Fetched dinosaur data: ${dino.name}`);
const paddockStatus = await checkPaddockStatus(dino.paddockId);
console.log(`Paddock #${dino.paddockId} status: ${paddockStatus.status}`);
if (!paddockStatus.isSecure) {
throw new SecuritySystemError(
`Cannot activate dinosaur: Paddock #${dino.paddockId} is not secure`,
"paddock-security"
);
}
const result = await updateDinosaurStatus(id, "active");
console.log(`Dinosaur status updated: ${result.status}`);
return {
success: true,
message: `Dinosaur #${id} successfully activated`,
dino
};
} catch (error) {
console.error(`Error during activation of dinosaur #${id}:`, error.message);
if (error instanceof SecuritySystemError) {
await activateSecurityAlarm(error.systemId, error.message);
}
return {
success: false,
message: `Failed to activate dinosaur #${id}`,
error: error.message
};
}
}This syntax is much more readable than .then().catch() chains and allows a more natural approach to error handling.
Advanced Error Handling Strategies
1. Retry Pattern
For network operations or communication with external systems, it is often worth retrying when a temporary error occurs:
async function withRetry(operation, options = {}) {
const {
maxAttempts = 3,
delay = 1000,
delayMultiplier = 2,
logging = true
} = options;
let lastError;
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
if (logging && attempt > 1) {
console.log(`Attempt ${attempt}/${maxAttempts}...`);
}
return await operation(attempt);
} catch (error) {
lastError = error;
if (logging) {
console.warn(`Attempt ${attempt}/${maxAttempts} failed:`, error.message);
}
if (attempt < maxAttempts) {
const waitTime = delay * Math.pow(delayMultiplier, attempt - 1);
if (logging) {
console.log(`Waiting ${waitTime}ms before next attempt...`);
}
await new Promise(resolve => setTimeout(resolve, waitTime));
}
}
}
throw lastError;
}
// Example usage
async function fetchSensorNodeData(nodeId) {
return withRetry(
async (attempt) => {
console.log(`Attempt ${attempt}: Fetching data from node #${nodeId}...`);
const response = await fetch(`https://sensor-api.jurassic-park.com/node/${nodeId}`);
if (!response.ok) {
throw new Error(`HTTP response: ${response.status}`);
}
return await response.json();
},
{
maxAttempts: 5,
delay: 2000,
delayMultiplier: 1.5
}
);
}2. Circuit Breaker Pattern
This pattern prevents repeated attempts at operations that consistently fail:
class CircuitBreaker {
constructor(options = {}) {
this.failureThreshold = options.failureThreshold || 3;
this.resetTimeout = options.resetTimeout || 30000;
this.state = 'CLOSED'; // CLOSED, OPEN, HALF_OPEN
this.failureCount = 0;
this.nextAttempt = Date.now();
this.onStateChange = options.onStateChange || (() => {});
}
async execute(fn) {
if (this.state === 'OPEN') {
if (Date.now() > this.nextAttempt) {
this.changeState('HALF_OPEN');
} else {
throw new Error('Circuit breaker is OPEN');
}
}
try {
const result = await fn();
this.onSuccess();
return result;
} catch (error) {
this.onFailure(error);
throw error;
}
}
onSuccess() {
this.failureCount = 0;
if (this.state === 'HALF_OPEN') {
this.changeState('CLOSED');
}
}
onFailure(error) {
this.failureCount += 1;
if (this.state === 'HALF_OPEN' || this.failureCount >= this.failureThreshold) {
this.changeState('OPEN');
}
}
changeState(state) {
this.state = state;
this.onStateChange(state);
if (state === 'OPEN') {
this.nextAttempt = Date.now() + this.resetTimeout;
}
}
}
// Example usage
const breaker = new CircuitBreaker({
failureThreshold: 3,
resetTimeout: 10000,
onStateChange: (newState) => {
console.log(`Circuit breaker changed state to: ${newState}`);
if (newState === 'OPEN') {
sendSystemAlert("Sensor system is unavailable");
}
}
});
async function fetchSensorData(sensorId) {
try {
return await breaker.execute(async () => {
const response = await fetch(`https://sensor-api.jurassic-park.com/sensor/${sensorId}`);
if (!response.ok) {
throw new Error(`HTTP Error: ${response.status}`);
}
return response.json();
});
} catch (error) {
if (error.message === 'Circuit breaker is OPEN') {
console.log(`Sensor #${sensorId} unavailable. Using cached data.`);
return fetchFromCache(sensorId);
}
throw error;
}
}3. Fallback Pattern
This pattern provides an alternative data source or functionality when the primary source fails:
async function fetchDinosaurDataWithFallback(dinoId) {
try {
// Try fetching from the primary database
return await fetchFromPrimaryDatabase(dinoId);
} catch (error) {
console.warn(`Failed to fetch from primary database: ${error.message}`);
try {
// Try fetching from the backup database
console.log(`Trying backup database...`);
return await fetchFromBackupDatabase(dinoId);
} catch (fallbackError) {
console.warn(`Failed to fetch from backup database: ${fallbackError.message}`);
try {
// Try fetching from local cache
console.log(`Trying local cache...`);
return await fetchFromLocalCache(dinoId);
} catch (cacheError) {
console.error(`All data sources failed!`);
// Return minimal data so the application can still function
return {
id: dinoId,
name: `Unknown Dinosaur #${dinoId}`,
species: "Unknown",
warning: "Incomplete data - all data sources failed"
};
}
}
}
}4. Bulkhead Pattern
This pattern isolates resources into dedicated pools so a failure in one part of the system does not affect other parts:
class Bulkhead {
constructor(options = {}) {
this.maxConcurrent = options.maxConcurrent || 10;
this.maxQueued = options.maxQueued || 20;
this.active = 0;
this.queue = [];
}
async execute(fn) {
if (this.active >= this.maxConcurrent) {
if (this.queue.length >= this.maxQueued) {
throw new Error('Bulkhead overflow: Too many requests queued');
}
// Add to queue
return new Promise((resolve, reject) => {
this.queue.push({ fn, resolve, reject });
});
}
this.active += 1;
try {
const result = await fn();
return result;
} catch (error) {
throw error;
} finally {
this.active -= 1;
// Handle queued tasks if available
if (this.queue.length > 0) {
const request = this.queue.shift();
this.execute(request.fn).then(request.resolve).catch(request.reject);
}
}
}
}
// Creating separate bulkheads for different subsystems
const securityBulkhead = new Bulkhead({ maxConcurrent: 5, maxQueued: 10 });
const feedingBulkhead = new Bulkhead({ maxConcurrent: 3, maxQueued: 5 });
const monitoringBulkhead = new Bulkhead({ maxConcurrent: 10, maxQueued: 30 });
// Usage
async function monitorPaddock(paddockId) {
return monitoringBulkhead.execute(async () => {
return await fetchMonitoringData(paddockId);
});
}
async function updateSecurity(paddockId, settings) {
return securityBulkhead.execute(async () => {
return await updateSecuritySettings(paddockId, settings);
});
}5. Error Middleware
In Express/Node.js applications, you can implement middleware for centralized error management:
// Centralized error handling middleware
function errorHandler(err, req, res, next) {
// Log the error
console.error("Error occurred:", err);
// Check error type
if (err instanceof SecuritySystemError) {
// Special treatment for security errors
activateSecurityProtocol(err);
return res.status(500).json({
error: "Security system error",
code: "SECURITY_FAILURE",
message: err.message
});
} else if (err.name === "ValidationError") {
// Validation errors
return res.status(400).json({
error: "Data validation error",
details: err.details,
message: err.message
});
} else if (err.name === "UnauthorizedError") {
// Authorization errors
return res.status(401).json({
error: "Unauthorized",
message: "You do not have permission to perform this operation"
});
}
// Default error handling
res.status(500).json({
error: "Internal server error",
message: process.env.NODE_ENV === "production" ?
"Sorry, something went wrong" : err.message
});
}
// Usage in Express
app.use(errorHandler);Error Handling Best Practices
Always handle errors - every async function should have some form of error handling.
Use specific error types - create dedicated error classes for different types of problems.
Provide useful messages - an error should contain information useful for diagnosing the problem.
Log errors centrally - use logging systems that allow centralized collection and analysis of errors.
Never ignore errors - if you catch an error and do not need to handle it further, at least log it.
Preserve the call stack - when throwing new errors, preserve the original call stacks.
try {
await riskyOperation();
} catch (error) {
// Preserving the original call stack
throw new Error(`Failed to execute operation: ${error.message}`, { cause: error });
}Handle errors at the right level - not all errors should be handled in the same place.
Use try...finally - use the
finallyblock to clean up resources regardless of whether an error occurred.Do not overload with information - do not show users detailed error information that does not concern them.
Prepare for the unexpected - always have a contingency plan for unexpected errors.
Summary
Proper error handling is a critical element of building reliable applications. In the context of Jurassic Park, where visitor safety and valuable specimens are at stake, this is even more important.
Good error handling:
- Ensures the system will operate even in case of problems
- Makes it easier to diagnose and fix problems
- Improves the user experience
- Prevents cascading failures
Remember that in the world of software, just as in Jurassic Park, it is always better to "expect the unexpected" and be prepared for it.
Code for this lesson: index.js
// Module Pattern - Module pattern
console.log("MODULE PATTERN - PARK MANAGEMENT SYSTEM\n");
// Module Pattern - encapsulating data and methods
const DinosaurPark = (function() {
// Private variables and functions
let dinosaurs = [];
let capacity = 20;
let isOpen = false;
function validateCapacity() {
return dinosaurs.length < capacity;
}
function generateId() {
return 'DINO-' + Date.now() + '-' + Math.floor(Math.random() * 1000);
}
// Public interface (API)
return {
addDinosaur: function(species, name) {
if (!validateCapacity()) {
console.log(`Cannot add ${species}. Park is full! (${dinosaurs.length}/${capacity})`);
return false;
}
const dinosaur = {
id: generateId(),
species: species,
name: name,
addedAt: new Date().toLocaleTimeString()
};
dinosaurs.push(dinosaur);
console.log(`Added: ${species} "${name}" (ID: ${dinosaur.id})`);
return true;
},
removeDinosaur: function(id) {
const index = dinosaurs.findIndex(d => d.id === id);
if (index !== -1) {
const removed = dinosaurs.splice(index, 1)[0];
console.log(`Removed: ${removed.species} "${removed.name}"`);
return true;
}
console.log(`No dinosaur found with ID: ${id}`);
return false;
},
listDinosaurs: function() {
console.log(`\n=== DINOSAUR LIST (${dinosaurs.length}/${capacity}) ===`);
if (dinosaurs.length === 0) {
console.log("Park is empty");
return;
}
dinosaurs.forEach((dino, index) => {
console.log(`${index + 1}. ${dino.species} "${dino.name}" - ID: ${dino.id}`);
});
},
openPark: function() {
if (dinosaurs.length === 0) {
console.log("Cannot open an empty park!");
return false;
}
isOpen = true;
console.log(`Park open! Welcome visitors!`);
return true;
},
closePark: function() {
isOpen = false;
console.log(`Park closed.`);
},
getStatus: function() {
return {
isOpen: isOpen,
dinosaurCount: dinosaurs.length,
capacity: capacity,
occupancy: ((dinosaurs.length / capacity) * 100).toFixed(1) + '%'
};
}
};
})();
// Using the module
console.log("=== ADDING DINOSAURS ===\n");
DinosaurPark.addDinosaur('T-Rex', 'Rexy');
DinosaurPark.addDinosaur('Velociraptor', 'Blue');
DinosaurPark.addDinosaur('Triceratops', 'Trike');
DinosaurPark.listDinosaurs();
console.log("\n=== PARK STATUS ===\n");
console.log(DinosaurPark.getStatus());
console.log("\n=== OPENING THE PARK ===\n");
DinosaurPark.openPark();
// Attempt to access private variables
// console.log(dinosaurs); // ERROR! dinosaurs is private
// console.log(capacity); // ERROR! capacity is privateDocs 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. How do you handle an error in an async function?
Hands-on tasks in the game
- Code editor
Write an async function with a try/catch block that attempts to fetch data from a sensor and gracefully handles connection errors.
- Vertical ordering
Arrange the stages of a Promise lifecycle: