Skip to lesson

TypeScript · Lesson 37 of 42

Handling errors safely with unknown

Catch errors safely, understand why the catch variable is unknown, narrow it with instanceof, write custom error classes, and attach a cause.

Beginner to advanced·14 min·Modules, async code and tooling·Updated 2026-11-24

UNDERSTAND IT. THEN TRY IT.

What you can do after this lesson

You will handle failures without trusting what was thrown, build your own error types, and decide when an error should be thrown and when it should simply be returned. Error handling is where optimistic code meets reality, and TypeScript's strictness here saves real bugs.

Anything can be thrown

In JavaScript, you can throw any value, not only error objects:

typescript
function risky(kind: number): void {
  if (kind === 1) throw new Error("an Error object");
  if (kind === 2) throw "a plain string";
  throw 404;
}

for (const kind of [1, 2, 3]) {
  try {
    risky(kind);
  } catch (e) {
    console.log(typeof e, e instanceof Error);
  }
}
result
object true
string false
number false

Because anything may arrive in a catch clause, TypeScript types the variable as unknown when strict is on (the option behind this is useUnknownInCatchVariables). You cannot use it until you check what it is:

typescript
try {
  JSON.parse("{ not valid");
} catch (e) {
  console.log(e.message);
}
result
example.ts(4,15): error TS18046: 'e' is of type 'unknown'.

Narrowing the caught value

The standard fix is an instanceof Error check, which narrows unknown to Error:

typescript
try {
  JSON.parse("{ not valid");
} catch (e) {
  if (e instanceof Error) {
    console.log("Error:", e.name);
  } else {
    console.log("Something else was thrown:", e);
  }
}
result
Error: SyntaxError

Writing that everywhere gets repetitive, so many projects keep one small helper that turns anything into a message:

typescript
function toMessage(error: unknown): string {
  if (error instanceof Error) {
    return error.message;
  }
  if (typeof error === "string") {
    return error;
  }
  return "Unknown error";
}

try {
  throw "disk full";
} catch (e) {
  console.log(toMessage(e));
}
result
disk full

Custom error classes

Subclassing Error lets you create failures that callers can tell apart, and attach extra data:

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

class NotFoundError extends Error {
  constructor(public resource: string) {
    super(`${resource} not found`);
    this.name = "NotFoundError";
  }
}

function load(id: number): string {
  if (id < 0) throw new ValidationError("id must be positive", "id");
  if (id > 100) throw new NotFoundError("user");
  return "user " + id;
}

for (const id of [5, -1, 500]) {
  try {
    console.log(load(id));
  } catch (e) {
    if (e instanceof ValidationError) {
      console.log(`Invalid ${e.field}: ${e.message}`);
    } else if (e instanceof NotFoundError) {
      console.log(`Missing ${e.resource}`);
    } else {
      throw e;
    }
  }
}
result
user 5
Invalid id: id must be positive
Missing user

Each instanceof check narrows to a specific class, so e.field and e.resource are available. The final else { throw e; } is an important habit: if you do not know how to handle a failure, rethrow it rather than swallowing it.

Adding a cause

When you catch an error and throw a new one, keep the original with the cause option, so the chain of causes is not lost:

typescript
function readConfig(text: string): unknown {
  try {
    return JSON.parse(text);
  } catch (error) {
    throw new Error("Could not read the configuration", { cause: error });
  }
}

try {
  readConfig("{ broken");
} catch (e) {
  if (e instanceof Error) {
    console.log(e.message);
    console.log(e.cause instanceof Error ? "cause: " + e.cause.name : "no cause");
  }
}
result
Could not read the configuration
cause: SyntaxError

The cause option is available in modern JavaScript, and the compiler needs a lib of ES2022 or later to know about it.

Throw or return?

Not every failure deserves an exception. A useful split:

  • Throw for unexpected problems that the caller cannot sensibly continue from, such as a corrupted file or a programming mistake.
  • Return a result for expected failures, such as validation of user input or "user not found", where the caller is meant to handle both outcomes.

For the second kind, the discriminated union pattern from the earlier lesson makes the failure part of the type, so the compiler forces callers to handle it:

typescript
type Result<T> =
  | { ok: true; value: T }
  | { ok: false; error: string };

function parsePort(input: string): Result<number> {
  const port = Number(input);
  if (!Number.isInteger(port) || port < 1 || port > 65535) {
    return { ok: false, error: `"${input}" is not a valid port` };
  }
  return { ok: true, value: port };
}

for (const text of ["8080", "http", "99999"]) {
  const result = parsePort(text);
  console.log(result.ok ? `port ${result.value}` : result.error);
}
result
port 8080
"http" is not a valid port
"99999" is not a valid port

finally

A finally block runs whether or not an error occurred, which is the right place to release resources such as open files or connections:

typescript
function work(shouldFail: boolean): void {
  try {
    console.log("start");
    if (shouldFail) throw new Error("boom");
    console.log("done");
  } catch {
    console.log("recovered");
  } finally {
    console.log("cleanup");
  }
}

work(false);
work(true);
result
start
done
cleanup
start
recovered
cleanup

Notice catch without a variable, which is allowed when you do not need the error.

Common mistakes

Assuming the caught value is an Error. It may be anything. Narrow it first.

Swallowing errors. An empty catch hides bugs. Handle it, log it or rethrow it.

Throwing strings. Throw Error objects, because they carry a stack trace.

Forgetting to keep the original error. Use cause when wrapping.

Using exceptions for normal outcomes. "Not found" in a search is not exceptional. Return a result.

Exercise

Write a parseJson(text: string): Result<unknown> that never throws. Write a custom HttpError class with a status property and a function that throws it for status codes 400 and above. Catch it, narrow it with instanceof, and print the status. Finally, write toMessage and test it with an Error, a string and null.

Next: Working with the DOM and events in TypeScript.

KNOWLEDGE CHECK

A quick check. You’ve got this.

Try each question. Every answer comes with an explanation.

0 / 4 understood
01 What is the type of e in catch (e) under strict mode?
02 Why is that type sensible?
03 How do you safely read the message of a caught value?
04 What does extends Error give a custom error class?

Ready for the next small win?

Mark the lesson complete when you are ready.

Course navigation

Frontend

TypeScript tutorial

Add types to JavaScript to catch mistakes before your code runs, from your first annotation to generics and real projects.

Your progress 0/42
Learning something new?Explore all courses