Typed Errors, Custom Classes, and Safe Exceptions - Textnotes

Typed Errors, Custom Classes, and Safe Exceptions


Learn how to handle errors effectively in TypeScript with typed error objects, custom error classes, and safe exception handling. This module provides practical examples for building robust and maintainable applications.

1. Typing Error Objects

TypeScript allows you to type error objects to ensure safe access to their properties.

Basic Example


try {
throw new Error("Something went wrong");
} catch (err) {
if (err instanceof Error) {
console.log(err.message); // Type-safe access
}
}

Benefits

  1. Ensures only valid properties are accessed.
  2. Prevents runtime errors due to undefined or incorrect types.

2. Custom Error Classes

Creating custom error classes helps differentiate between different types of errors.

Example


class ValidationError extends Error {
constructor(message: string) {
super(message);
this.name = "ValidationError";
}
}

function validateAge(age: number) {
if (age < 18) {
throw new ValidationError("Age must be 18 or older");
}
}

try {
validateAge(16);
} catch (err) {
if (err instanceof ValidationError) {
console.log("Validation failed:", err.message);
} else if (err instanceof Error) {
console.log("General error:", err.message);
}
}

Custom error classes make it easier to handle specific scenarios and improve code readability.

3. Safe Exception Handling

Safe exception handling ensures the application does not crash unexpectedly and errors are managed properly.

Guidelines

  1. Always check the type of the error object.
  2. Avoid using any for error objects.
  3. Use custom error classes for predictable error handling.
  4. Provide fallback or recovery logic when possible.

Example


function parseJson(json: string) {
try {
return JSON.parse(json);
} catch (err) {
if (err instanceof SyntaxError) {
console.error("Invalid JSON:", err.message);
return null;
} else {
throw err;
}
}
}

const data = parseJson("{ invalid json }"); // Logs: Invalid JSON: Unexpected token i in JSON

Conclusion

Error handling in TypeScript benefits from typed error objects, custom error classes, and safe exception handling practices. Using these techniques ensures predictable behavior, reduces runtime errors, and improves application reliability.