TS Error Handling

TypeScript Error Handling

Properly handling errors in JavaScript has always been an unpredictable and messy endeavor.

TypeScript provides incredible tools to strongly type your try/catch and error throwing blocks.

By default, caught errors are typed as unknown in modern TypeScript configurations.

This forces you to check the error's structure before attempting to read its message payload.


1. Typing the Catch Block

In older TypeScript versions, variables in a catch block defaulted directly to any.

Now, they default to unknown, meaning you cannot blindly use error.message anymore.

You must use the instanceof Error type guard to verify it is actually a standard Error object.

This prevents crashes caused when non-error values (like strings or null) are manually thrown.

Catch Block Example:

try {
  throw new Error("Database disconnected!");
} catch (error: unknown) {
  // We must verify the shape before logging it safely
  if (error instanceof Error) {
    console.error(error.message);
  } else {
    console.error("An unexpected unknown error occurred.");
  }
}

2. Custom Error Classes

To provide better structural clarity, you can create Custom Error classes extending standard Error.

This allows you to attach additional context like HTTP status codes or custom validation arrays.

You can then use instanceof to catch specific types of errors differently in your application.

It brings highly structured, Java-esque error handling to server-side Node architectures.

Custom Error Example:

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

try { throw new ValidationError("email", "Format is completely invalid."); } catch (err) { if (err instanceof ValidationError) { console.log(Fix field: ${err.field}); // Safely typed! } }


3. SEO and Resilient Uptime

Strict error boundaries ensure that unhandled exceptions never crash the entire user application.

By rendering graceful fallback UIs upon error, users stay on your website significantly longer.

Search engines highly penalize domains that consistently serve broken pages or 500 status codes.

Strongly typed try/catch blocks are your ultimate safety net for protecting global site reliability.

Result Object Pattern:

// Alternatively, return a strongly typed Result object instead of throwing!
type Result<T> = { success: true; data: T } | { success: false; error: string };

Exercise

?

What is the default type of the error variable in a strict TypeScript catch block?


4. Final Thoughts

Congratulations, you have now mastered the advanced principles and ecosystem of TypeScript!

Handling dynamic errors robustly elevates your systems to enterprise-grade quality.

Keep building, stay curious, and always keep your types strict!