/**
* Error Object Example in TypeScript
* ----------------------------------
* Demonstrates:
* - Creating Error objects
* - Throwing errors
* - Catching errors
* - Custom Error classes
* - Error handling functions
* - Type-safe error processing
*/
/*
Key concepts include
--------------------
TypeScript
throw
try
catch
finally
Error
CustomError
instanceof Error
*/
"use strict";
/**
* Custom error type for validation failures.
*/
class ValidationError extends Error {
constructor(message: string) {
super(message);
this.name = "ValidationError";
}
}
/**
* Validates an age value.
*
* @param age User age
* @returns true when valid
* @throws ValidationError
*/
function validateAge(age: number): boolean {
if (age < 0) {
throw new ValidationError(
"Age cannot be negative."
);
}
if (age > 130) {
throw new ValidationError(
"Age is outside the valid range."
);
}
return true;
}
/**
* Safely divides two numbers.
*
* @param dividend First number
* @param divisor Second number
* @returns Division result
* @throws Error
*/
function divide(
dividend: number,
divisor: number
): number {
if (divisor === 0) {
throw new Error(
"Division by zero is not allowed."
);
}
return dividend / divisor;
}
/**
* Demonstrates centralized error handling.
*
* @param error Unknown error object
*/
function handleError(error: unknown): void {
if (error instanceof Error) {
console.error(
`Error Type: ${error.name}`
);
console.error(
`Message: ${error.message}`
);
if (error.stack) {
console.error(
`Stack Trace:\n${error.stack}`
);
}
} else {
console.error(
"An unknown error occurred."
);
}
}
// ----------------------------------------------------
// Creating an Error Object
// ----------------------------------------------------
console.log("=== Create Error Object ===");
const error: Error = new Error(
"Something went wrong."
);
console.log(error.name);
console.log(error.message);
// ----------------------------------------------------
// Example 1: Division
// ----------------------------------------------------
console.log("\n=== Division Example ===");
try {
const result: number =
divide(10, 2);
console.log("Result:", result);
} catch (error: unknown) {
handleError(error);
}
// ----------------------------------------------------
// Example 2: Division by Zero
// ----------------------------------------------------
console.log("\n=== Division by Zero ===");
try {
const result: number =
divide(10, 0);
console.log(result);
} catch (error: unknown) {
handleError(error);
}
// ----------------------------------------------------
// Example 3: Validation
// ----------------------------------------------------
console.log("\n=== Validation Example ===");
try {
validateAge(25);
console.log(
"Age validation successful."
);
} catch (error: unknown) {
handleError(error);
}
// ----------------------------------------------------
// Example 4: Invalid Age
// ----------------------------------------------------
console.log("\n=== Invalid Age ===");
try {
validateAge(-10);
} catch (error: unknown) {
handleError(error);
}
// ----------------------------------------------------
// Example 5: Another Invalid Age
// ----------------------------------------------------
console.log("\n=== Invalid Range ===");
try {
validateAge(200);
} catch (error: unknown) {
handleError(error);
}
// ----------------------------------------------------
// Example 6: Working with Error Properties
// ----------------------------------------------------
console.log("\n=== Error Properties ===");
const customError: Error =
new Error("Custom error example.");
console.log("Name:", customError.name);
console.log("Message:", customError.message);
console.log(
"Has Stack:",
customError.stack !== undefined
);
// ----------------------------------------------------
// Example 7: Finally Block
// ----------------------------------------------------
console.log("\n=== Finally Example ===");
try {
console.log("Processing...");
throw new Error("Process failed.");
} catch (error: unknown) {
handleError(error);
} finally {
console.log(
"Cleanup logic executed."
);
}
/*
run:
=== Create Error Object ===
Error
Something went wrong.
=== Division Example ===
Result: 5
=== Division by Zero ===
=== Validation Example ===
Age validation successful.
=== Invalid Age ===
=== Invalid Range ===
=== Error Properties ===
Name: Error
Message: Custom error example.
Has Stack: true
=== Finally Example ===
Processing...
Cleanup logic executed.Error Type: Error
Message: Division by zero is not allowed.
Stack Trace:
Error: Division by zero is not allowed.
Error Type: ValidationError
Message: Age cannot be negative.
Stack Trace:
ValidationError: Age cannot be negative.
Error Type: ValidationError
Message: Age is outside the valid range.
Stack Trace:
ValidationError: Age is outside the valid range.
Error Type: Error
Message: Process failed.
Stack Trace:
Error: Process failed.
*/