Error Handling Patterns in TypeScript: Beyond Try-Catch
Error Handling Patterns in TypeScript: Beyond Try-Catch Try-catch blocks scattered everywhere. No idea what errors a function can throw. Callers forget to handle edge cases. Here are better pattern...

Source: DEV Community
Error Handling Patterns in TypeScript: Beyond Try-Catch Try-catch blocks scattered everywhere. No idea what errors a function can throw. Callers forget to handle edge cases. Here are better patterns. The Result Type Instead of throwing, return a discriminated union: type Result<T, E = Error> = | { ok: true; value: T } | { ok: false; error: E }; function divide(a: number, b: number): Result<number, string> { if (b === 0) return { ok: false, error: "Division by zero" }; return { ok: true, value: a / b }; } const result = divide(10, 0); if (result.ok) { console.log(result.value); // TypeScript knows this is number } else { console.error(result.error); // TypeScript knows this is string } Custom Error Classes class AppError extends Error { constructor( message: string, public code: string, public statusCode: number = 500, public isOperational: boolean = true ) { super(message); this.name = "AppError"; } } class NotFoundError extends AppError { constructor(resource: string, id: