DEV Community

Cover image for Handling Errors in TypeScript: Why Use unknown in catch (e: unknown)
Jean Lucas
Jean Lucas

Posted on • Edited on

3

Handling Errors in TypeScript: Why Use unknown in catch (e: unknown)

When dealing with exceptions in TypeScript, it’s common to see something like this:

try {
  // Desired logic.
} catch (e) {
  console.error(e.message); // This can cause an error!
}
Enter fullscreen mode Exit fullscreen mode

By default, TypeScript assumes that (e) is of type any. However, common errors such as 403, 404, 500, 504, and many others can trigger exceptions, and they don’t always share the same response structure. This can lead to runtime issues if you try to handle the error in a user-friendly way without properly validating its type.

Why Use unknown ?

The unknown type was introduced as a safer alternative to any. It prevents us from performing direct operations on a variable without first verifying its type, forcing us to handle errors correctly before accessing any properties.

Correct Error Handling Example:

try {
  // Desired logic.
} catch (e: unknown) {
  if (e instanceof Error) {
    console.error(e.message); // Now it's safe to access .message
  } else {
    console.error("Unknown error:", e);
  }
}
Enter fullscreen mode Exit fullscreen mode

With this approach, we prevent unknown errors from breaking our application and ensure that unexpected issues don’t escape our control or get directly exposed to the end user.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay