Nov 23, 20265 min read

Error Handling in TypeScript APIs

How to separate expected errors from bugs in a TypeScript backend: domain error types, one place that maps them to HTTP responses, safe messages, logging that keeps the cause, and what clients should retry, with examples on Encore.

Illustration for Error Handling in TypeScript APIs

An API can fail in two ways that look alike in a stack trace and need opposite handling. A missing order is expected and deserves a 404, while a null pointer in your own code is a bug and deserves a generic 500 and a log line you can act on.

Mixing the two sends stack traces to clients, turns validation failures into 500s and hides real bugs as "not found".

What does a good error setup contain?

PartRuleWhat goes wrong without it
Domain errorsTyped errors thrown by business codeBusiness code knows about HTTP
One mapperA single place that turns errors into responsesInconsistent status codes per endpoint
Safe messagesClients see a code and a message you wroteStack traces and SQL in responses
LoggingLog unexpected errors with cause and contextBugs vanish behind a generic 500
Retry semantics4xx is final, 429 and 503 can be retriedClients hammer a failing endpoint

How do you type errors?

Throw errors that describe what happened in the domain, not in HTTP. A service function that cannot find an order throws NotFound, and does not know what a 404 is. That keeps the same code usable from a queue consumer, a script or a test.

export type ErrorKind = "not_found" | "conflict" | "invalid"; export class DomainError extends Error { constructor( readonly kind: ErrorKind, message: string, readonly details?: Record<string, unknown>, ) { super(message); this.name = "DomainError"; } } export const notFound = (what: string) => new DomainError("not_found", `${what} not found`);

Why is the catch variable unknown?

JavaScript lets code throw anything, so a catch block cannot assume an Error. With useUnknownInCatchVariables, part of strict, the caught value is unknown, and you narrow it with instanceof before reading message. Treat anything that is not a DomainError as an unexpected failure. Also make sure promise rejections are always awaited or caught, because an unhandled rejection can terminate a Node.js process by default.

What should the response look like?

Pick one shape and use it everywhere: RFC 9457 defines a standard "problem details" format for HTTP APIs with a type, title, status and detail, and a simpler { code, message, details } object works as long as it is consistent. Keep the message safe to show, put machine-readable data in details, and never include stack traces, SQL or internal hostnames.

Which errors should clients retry?

A 4xx means the request itself must change, so retrying it is pointless. 429 and 503 are the signal to back off and try again, and network failures and timeouts can be retried when the operation is idempotent. See API idempotency keys for making retries safe and API rate limiting for the 429 side.

How do you build it with Encore?

Encore

Encore is a backend framework with built-in infrastructure, and its API errors already define the response shape: throw an APIError with a code, and Encore returns { "code": "not_found", "message": "...", "details": null } with the matching HTTP status. The codes follow gRPC, so they also carry across calls between services, and withDetails attaches structured data for clients. Endpoints stay type-safe and the mapper below is the only place that touches APIError.

Application code passes through Encore and infrastructure guardrails to resources provisioned in your own AWS or GCP account.
Encore provisions the infrastructure your application needs in your own AWS or GCP account.
Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

~
$ encore app create shop-api --example=ts/hello-world$ cd shop-api && mkdir -p orders
// orders/errors.ts import { APIError } from "encore.dev/api"; import log from "encore.dev/log"; export type ErrorKind = "not_found" | "conflict" | "invalid"; export class DomainError extends Error { constructor( readonly kind: ErrorKind, message: string, readonly details?: Record<string, unknown>, ) { super(message); this.name = "DomainError"; } } // The only place that knows about HTTP-facing errors. function toApiError(err: unknown): APIError { if (err instanceof APIError) return err; if (err instanceof DomainError) { const api = err.kind === "not_found" ? APIError.notFound(err.message) : err.kind === "conflict" ? APIError.alreadyExists(err.message) : APIError.invalidArgument(err.message); return err.details ? api.withDetails(err.details) : api; } // A bug: keep the cause in the logs and give the client nothing internal. log.error(err instanceof Error ? err : new Error(String(err)), "unexpected error"); return APIError.internal("something went wrong"); } export async function handle<T>(fn: () => Promise<T>): Promise<T> { try { return await fn(); } catch (err) { throw toApiError(err); } }
// orders/orders.ts import { api } from "encore.dev/api"; import { SQLDatabase } from "encore.dev/storage/sqldb"; import { DomainError, handle } from "./errors"; const db = new SQLDatabase("orders", { migrations: "./migrations" }); interface Order { id: number; status: string; } async function findOrder(id: number): Promise<Order> { const row = await db.queryRow<Order>`SELECT id, status FROM orders WHERE id = ${id}`; if (!row) throw new DomainError("not_found", "order not found", { id }); return row; } export const get = api( { expose: true, method: "GET", path: "/orders/:id" }, async ({ id }: { id: number }): Promise<Order> => handle(() => findOrder(id)), );

encore run starts a local Postgres, and a test can call get with a missing ID and assert a not_found code, and a failing query to check that the client gets internal while the log keeps the cause. On deploy, the database runs on RDS or Cloud SQL in your own AWS or GCP account as the AWS infrastructure docs describe. A coding agent adding an endpoint reuses handle and throws domain errors, so every new endpoint returns the same response shape without extra instructions.

Best fit: Teams that want consistent error responses across many endpoints and services without repeating the mapping in each handler.

Frequently asked questions

How should you structure errors in a TypeScript API?

Throw typed domain errors from your business code, such as NotFound or Conflict, and translate them to HTTP responses in one place at the edge. Anything that is not one of your error types is a bug, so log it with its stack and return a generic internal error to the client.

Why is the catch variable unknown in TypeScript?

Anything can be thrown in JavaScript, including strings and objects that are not Error instances. With useUnknownInCatchVariables, enabled by strict, you must narrow the value with instanceof before reading its message, which stops code from assuming a shape it does not have.

Which HTTP status codes should an API return for errors?

Use 400 for invalid input, 401 when authentication is missing, 403 when the caller lacks permission, 404 for a missing resource, 409 for conflicts such as duplicates, 429 for rate limits and 500 or 503 for server problems. Clients should retry only the 429, 503 and network failures.

How does Encore return errors from TypeScript endpoints?

With Encore, throw an APIError with a code such as notFound or invalidArgument. Encore returns a JSON body with code, message and details and the matching HTTP status, and error codes follow gRPC so they also work between services.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders