Skip to content
Tutorials Center
My learning

Topics

Lesson 54 of 96 ยท Async and Errors

Error Handling

Handle errors safely in TypeScript - unknown catch variables, narrowing, custom error classes, Error cause, never, and the Result pattern vs exceptions.

TypeScript checks the values you pass around, but there's one channel it can't see into: exceptions. Any function can throw, a thrown value can be anything at all, and nothing in a function's type says that it might throw. That's why error handling needs some deliberate habits in TypeScript, more than in most other parts of the language.

This lesson covers those habits. You'll see why a catch variable is typed unknown, how to narrow it into something useful, how to build custom error classes that carry typed data, how to chain errors with cause, and when to skip exceptions entirely and return a typed Result instead. If you need a refresher on try, catch, finally and throw themselves, see the JavaScript lessons on errors and throwing errors.

Why catch gives you unknown

In JavaScript you can throw anything: an Error, a string, a number, null, a plain object. Libraries really do throw strings sometimes, and code that runs inside other code (callbacks, plugins, eval) can throw values you never anticipated. So when TypeScript reaches a catch clause, it honestly doesn't know what it caught.

With strict on, the useUnknownInCatchVariables flag types the catch variable as unknown (without it, the variable is any). You must narrow an unknown before using it, so this example fails on purpose:

TypeScript Using a caught error directly (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

TEXT
main.ts(4,35): error TS18046: 'error' is of type 'unknown'.
main.ts(9,17): error TS1196: Catch clause variable type annotation must be 'any' or 'unknown' if specified.

The second error shows that you can't simply declare catch (error: Error). TypeScript only allows any or unknown there, because an annotation would be a promise the compiler can't keep: nothing guarantees that the thrown value is an Error. The strict mode lesson shows this flag alongside the rest of the strict family.

Narrowing caught errors

The fix is to narrow the value. instanceof Error is the usual check, and once it passes you get message, name and stack. For everything else, convert the value to a string or wrap it. A small toError helper handles both cases in one place:

TypeScript Narrowing unknown errors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The output is Non-error thrown: disk quota exceeded, Bad JSON: SyntaxError and File is missing. Three patterns are worth copying:

  • Check the specific type you can handle. instanceof SyntaxError and the code === 'ENOENT' test match only the failures this code knows how to deal with.
  • Use in to reach extra properties. 'code' in error narrows error to a type that has a code property (of type unknown), so comparing it with a string is allowed.
  • Rethrow what you don't handle. A catch that swallows every error hides bugs. Handle the cases you expect and throw error for the rest.

instanceof can fail for errors created in another realm (an iframe, a Node vm context or a worker), because each realm has its own Error constructor. ES2026 adds Error.isError(value), which recognizes real errors from any realm. It works in Node 24 and current browsers, and TypeScript's esnext library types it as a type guard, so if (Error.isError(error)) narrows just like instanceof. For older targets, instanceof Error remains the standard check.

Promise rejections follow the same rule. Inside try { await ... } catch (error) the variable is unknown. In a .catch((reason) => ...) callback, the reason parameter is typed any for historical reasons, so it's good practice to annotate it yourself: .catch((reason: unknown) => ...). The promises lesson shows this with allSettled.

Custom error classes

When your own code fails, throw instances of your own error classes. A subclass of Error can carry typed data about the failure (a status code, the field that was invalid, the id that wasn't found), and instanceof narrows to the exact class, giving callers access to that data:

TypeScript An error class hierarchy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

A few details make these classes work well:

  • Set name. String(error), stack traces and loggers print name: message, so NotFoundError: Order #42 was not found is far more useful than a generic Error:. The override keyword documents that name already exists on Error (and is required under noImplicitOverride; see inheritance).
  • Use parameter properties like readonly resource: string to store failure details with no boilerplate (classes covers the syntax).
  • Build a hierarchy with a base class like AppError, so a top-level handler can say "any error from our own code" with one instanceof check.

instanceof checks on Error subclasses work correctly because our target is ES2024, where TypeScript emits real class syntax. Very old targets (ES5) compiled classes into functions, and subclasses of Error lost their prototype unless you called Object.setPrototypeOf(this, new.target.prototype) in the constructor. TypeScript 7 removed the ES5 target, so you only need that line when reading old code.

Custom errors in an HTTP API

A server has to turn failures into HTTP responses. A clean way is a small hierarchy of errors that carry a status code (and optional details), plus one central function that maps any caught error to a reply. Code deep in your handlers just throws NotFoundError; only the central handler knows about status codes and JSON.

TypeScript Centralized error handling

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Known errors keep their status (404, 422) and details, while anything unexpected, like the TypeError, becomes a generic 500 so internal messages never leak to clients. In a real framework the central function is the error middleware; see TypeScript with Fastify, Hono and Koa. Include useful metadata (a status, a machine-readable code, field details), log the original error on the server, and keep message safe to show.

Wrapping errors with cause

Low-level errors like "file not found" or "unexpected token" rarely mean much to whoever reads the log. A better message says what the program was trying to do: "could not load config". But replacing the original error throws away the details you need for debugging. The cause option (ES2022) keeps both. Pass { cause: original } as the second constructor argument and the new error remembers the old one:

TypeScript Chaining errors with cause

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The second input fails our own validation, and the third fails inside JSON.parse, but both reach the caller as a ConfigError with the real reason attached:

TEXT
port 8080
ConfigError: Could not load the server config
  caused by TypeError: "port" must be a number
ConfigError: Could not load the server config
  caused by SyntaxError: Expected property name or '}' in JSON at position 2 (line 1 column 3)

cause is typed unknown because, like a caught value, it could be anything. Custom error classes accept it automatically if their constructor passes an ErrorOptions object through to super(message, options). Node prints the whole chain when an error with a cause goes uncaught, and most logging tools do the same.

Functions that never return: never

A function that always throws has the return type never, meaning "this call never produces a value." TypeScript uses that information in control-flow analysis: code after a call to a never function is unreachable, so the compiler doesn't demand a return there. Helpers like fail() and the exhaustiveness check assertNever() rely on this:

TypeScript never-returning helpers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

If someone adds { kind: 'triangle'; ... } to Shape without a new case, assertNever(shape) stops compiling, because shape is no longer never in the default branch. The discriminated unions lesson uses this technique in depth.

Errors as values: the Result pattern

Exceptions have a weakness that matters in a typed language: they are invisible in function types. findUser(id: number): string doesn't tell you that it throws NotFoundError, so nothing reminds callers to handle it. One alternative is to return failures as ordinary values, using a discriminated union usually called Result:

TypeScript A typed Result instead of exceptions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Here the possible failures are part of the signature: Result<number, AgeError>. The caller can't reach result.value without first checking result.ok, and explain must handle every kind because its return type is string and the switch has no default. Add a fourth kind of error and both places tell you to update them.

Neither style wins everywhere. Most TypeScript code uses both:

Use exceptions when Use a Result when
The failure is a bug or truly unexpected (a broken invariant, a missing config file at startup) The failure is an expected outcome (invalid input, "not found", a declined payment)
The error must travel through many layers to one top-level handler The direct caller should decide what to do
You work with APIs that already throw (JSON.parse, fs, fetch) You want the compiler to force callers to handle each case

A common design is "Result inside, exceptions at the edges": domain functions return Results, and code that calls throwing APIs catches their errors and converts them into Results (or the other way round, at an HTTP boundary, turns an unhandled Result error into a 400 response). Libraries such as neverthrow and Effect build richer versions of this idea, but the dozen lines above are often all you need. The typed API client project uses this pattern end to end.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. With strict mode on, what is the type of e in catch (e) { }?

    useUnknownInCatchVariables, part of strict, types the catch variable as unknown because any value can be thrown. You must narrow it before use.
  2. 2. Does catch (e: TypeError) { } compile?

    TypeScript cannot guarantee what was thrown, so it only accepts any or unknown as an annotation. Narrow with instanceof inside the block instead.
  3. 3. Why should a custom error class set its name property?

    Error's toString and stack output start with name followed by message. instanceof works regardless; name is about readable diagnostics.
  4. 4. What is the type of error.cause for const error = new Error("x", { cause: original })?

    A cause can be any value, exactly like a thrown value, so TypeScript types it as unknown. Narrow it with instanceof Error before reading its properties.
  5. 5. What is the main advantage of returning Result<number, AgeError> instead of throwing?

    Exceptions are invisible in signatures. A Result is a discriminated union, so the compiler forces callers to check ok before reading value and to handle each error kind.

Summary

  • Anything can be thrown, so under strict (useUnknownInCatchVariables) a catch variable is unknown, and annotations other than any/unknown are rejected (TS1196).
  • Narrow caught values with instanceof Error (or Error.isError in ES2026 runtimes), reach extra properties with in, handle what you expect and rethrow the rest. Treat .catch reasons as unknown too.
  • Custom error classes extend Error, set name, and carry typed details through parameter properties; instanceof narrows to them.
  • new Error(message, { cause }) wraps a low-level error in a meaningful one without losing it; cause is typed unknown.
  • A function that always throws returns never, which control-flow analysis understands; assertNever turns missing cases into compile errors.
  • Exceptions don't appear in function types. For expected failures, return a Result<T, E> discriminated union so the compiler makes callers handle every case.

Next: Iterators and Generators