DEV Community

Cover image for Make TypeScript errors visible: Result types in Lambda handlers
Sascha Mirow-Stanitzok
Sascha Mirow-Stanitzok

Posted on Originally published at sascha-ms.de

Make TypeScript errors visible: Result types in Lambda handlers

A pattern I see in almost every code review: a Lambda handler with a large catch block, a cascade of instanceof checks and a generic 500 at the end for everything nobody thought of. Then someone adds a new error class, the handler does not know it, and a customer gets a 500 where a 409 would have been correct. The compiler never complained, because in TypeScript a thrown error is invisible in the signature.

I wrote a detailed guide on how I deal with this, TypeScript error handling: Result types, not throw, with a runnable bike rental example, tests and a serverless.yml. Here are the core ideas.

Why throw does not scale in TypeScript

A signature like Promise<Reservation> promises a reservation and says nothing about the ways it can fail. TypeScript has no checked exceptions, and JavaScript lets you throw literally anything. In strict mode the catch variable is therefore unknown, which is honest but does not help much. Callers have to read the source or guess.

Two kinds of errors, two tools

The distinction that makes everything else easier:

  • Expected errors belong to the business logic: the bike does not exist, it is already booked, the customer hit their reservation limit. They happen every day, and the caller has to react to each one specifically.
  • Failures are technical: the database does not answer, a timeout, a bug. The caller can only abort, log and maybe retry later.

My rule of thumb: expected errors are returned, failures are thrown.

A Result type in a handful of lines

For the returned errors you do not need a library. A discriminated union on an ok field is enough, and each error kind becomes a plain object with a kind field that carries exactly the data the caller needs:

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

type ReservationError =
  | { kind: 'BikeNotFound'; bikeId: string }
  | { kind: 'BikeUnavailable'; bikeId: string; freeFrom: string };

function toStatus(error: ReservationError): number {
  switch (error.kind) {
    case 'BikeNotFound': return 404;
    case 'BikeUnavailable': return 409;
    default: return assertNever(error); // compile error if a kind is missing
  }
}
Enter fullscreen mode Exit fullscreen mode

The assertNever helper only accepts values of type never. As long as every kind is handled, that holds. Add a new kind later and the build fails right there, instead of a customer finding out in production. That exhaustiveness check is, for me, the real payoff of the whole approach. Plain error objects are also easy to log as JSON and to compare in tests with deepEqual, which beats matching on error messages.

Do not wrap everything in a Result

Once people discover Result types, they are tempted to ban exceptions entirely. In Lambda that is a mistake. Lambda decides based on a thrown error whether to retry: asynchronous invocations are retried, SQS messages go back into the queue. If your handler turns an unreachable database into ok: false, Lambda sees a successful invocation, the retry never happens and the event is gone.

So failures keep flying as exceptions all the way up, ideally with the cause option to keep the original stack trace. The only places I catch locally are calls that throw for expected situations, such as JSON.parse on a broken body, or a third-party library that signals a domain problem with an exception.

Library or not?

Libraries like neverthrow add chaining helpers such as map and andThen. For a typical handler with three or four steps, I find early returns easier to read and prefer one dependency less. If your team chains many steps or likes functional patterns, a library is the better choice. What matters more than the choice: agree on a clear line as a team, for example "services return Results, repositories throw", and stick to it.

What the full article covers

  • The complete Result type with ok, err and assertNever, plus the business logic and input validation built on it
  • Mapping every error kind to HTTP status codes in a Lambda handler and what the compiler error looks like when a case is missing
  • Tests with the built-in Node.js test runner and deployment with Serverless Framework v4
  • A decision table for Result versus throw, common pitfalls and an FAQ

Read the full guide with all code on my site: TypeScript error handling: Result types, not throw

📖 This is the condensed version. The full article on sascha-ms.de goes deeper – with all code samples, diagrams and a short knowledge check.


👉 Next step: New here? My start page collects the best articles, tools and learning paths in one place.

📬 Stay updated: New articles on serverless, AI and leading tech teams via RSS, browser push or the weekly newsletter (in German).

Originally published on sascha-ms.de. More articles on serverless, AI in everyday development and leading tech teams: sascha-ms.de/en

Top comments (0)