---
title: "Error Handling and Input Validation in TypeScript Node.js APIs"
description: "Patterns for TypeScript Node.js APIs: a consistent error format, custom error classes, input validation with Zod, catching async errors and safe logging."
url: https://sanderyaz.com/en/blog/typescript-nodejs-api-error-handling/
author: Sander Yazıcıoğlu
date: 2026-12-02
updated: 2026-12-02
lang: en
tags: ["Node.js","TypeScript","Backend","API"]
---

# Error Handling and Input Validation in TypeScript Node.js APIs

An API shows its quality not when everything works but when something goes wrong. Inconsistent error messages, stack traces leaking to users and unhandled promises are both security and maintenance problems. This article covers the error-handling patterns I use in Node.js APIs written in TypeScript. The examples use Express, but the ideas carry over to Fastify and NestJS.

## Two kinds of errors

First, split errors into two groups:

- **Expected (operational) errors:** invalid input, missing records, unauthorised access, an external service timing out. These are part of the normal flow and should return a meaningful message.
- **Unexpected errors (bugs):** reading a field of `undefined`, a wrong assumption. Users shouldn't see details; these should be logged and raise an alert.

I make that distinction in code with a custom error class.

## A custom error class

```ts
export class AppError extends Error {
  constructor(
    public readonly status: number,
    public readonly code: string,
    message: string,
    public readonly details?: unknown
  ) {
    super(message);
    this.name = 'AppError';
  }
}

export const notFound = (what: string) => new AppError(404, 'not_found', `${what} not found`);
export const forbidden = () => new AppError(403, 'forbidden', 'You are not allowed to do this');
```

The `code` is for machines (clients check it); the `message` is for humans. Messages may change; codes are part of the contract.

## A consistent error format

Pick one format so clients can handle every error the same way. A standard option for HTTP APIs is the **RFC 9457 "Problem Details"** format:

```json
{
  "type": "https://api.example.com/errors/validation",
  "title": "Invalid input",
  "status": 400,
  "detail": "email is not a valid email address",
  "code": "validation_error"
}
```

You don't have to use this exact format; what matters is that **every** error comes back in the same shape.

## Validating input with Zod

TypeScript types exist at compile time; they don't validate incoming JSON. A schema library such as Zod gives you runtime validation and type inference together:

```ts
import { z } from 'zod';

export const CreateUser = z.object({
  email: z.string().email(),
  name: z.string().min(2).max(80),
  role: z.enum(['admin', 'member']).default('member')
});

export type CreateUserInput = z.infer<typeof CreateUser>;

export const validate = <T>(schema: z.ZodType<T>, data: unknown): T => {
  const result = schema.safeParse(data);
  if (!result.success) {
    throw new AppError(400, 'validation_error', 'Invalid input', result.error.flatten());
  }
  return result.data;
};
```

The schema becomes the single source of truth: the validation rule and the TypeScript type can't drift apart.

## Don't miss async errors

In Express 4, an error thrown inside an async route doesn't reach the error middleware on its own and can leave the request hanging. Express 5 fixed this: rejected promises returned from async handlers are now passed to the error middleware automatically. On Express 4, a small wrapper is enough:

```ts
import type { RequestHandler } from 'express';

export const asyncHandler = (handler: RequestHandler): RequestHandler =>
  (req, res, next) => Promise.resolve(handler(req, res, next)).catch(next);

router.post('/users', asyncHandler(async (req, res) => {
  const input = validate(CreateUser, req.body);
  const user = await users.create(input);
  res.status(201).json(user);
}));
```

## A central error middleware

Routing every error through one place keeps the format and logging consistent:

```ts
import type { ErrorRequestHandler } from 'express';

export const errorHandler: ErrorRequestHandler = (error, req, res, _next) => {
  if (error instanceof AppError) {
    return res.status(error.status).json({
      title: error.message,
      status: error.status,
      code: error.code,
      details: error.details
    });
  }

  req.log.error({ err: error, requestId: req.id }, 'Unhandled error');
  res.status(500).json({ title: 'Something went wrong', status: 500, code: 'internal_error', requestId: req.id });
};
```

Things to watch:

- **Never send stack traces to clients.** File paths, library versions and internals are valuable to attackers.
- **Return a request id.** When a user reports an error, you find that request in the logs in seconds.
- **Keep logs structured.** JSON loggers such as pino make searching and filtering easy.

## Don't log sensitive data

Writing the raw request body into error logs puts passwords, tokens and personal data into your logs. Mask sensitive fields in your logger (pino's `redact` option) and never log the `Authorization` header.

## The last line of defence at process level

```ts
process.on('unhandledRejection', (reason) => {
  logger.fatal({ reason }, 'Unhandled promise rejection');
  process.exit(1);
});
```

An unhandled error means the app is in an unknown state. Log it, exit, and let your process manager (Docker, Kubernetes, PM2) restart cleanly. Finishing in-flight requests before exiting (graceful shutdown) deserves its own plan.

## Timeouts and retries for external services

Many errors come from external services. Put a **timeout** on every outbound call (for example `AbortSignal.timeout(5000)`), retry only safe (idempotent) operations with **exponential backoff**, and consider a circuit breaker for a service that keeps failing.

## Conclusion

Good error handling is custom error classes, one error format, runtime validation, a central middleware and safe logging. The same patterns apply to realtime systems; in [realtime systems with Node.js and WebSocket](/en/blog/websocket-realtime-nodejs/) I type message contracts with the same mindset.

---

About the author: [Sander Yazıcıoğlu](https://sanderyaz.com/en/about/). Sander Yazıcıoğlu is a Senior Full-Stack Developer in Istanbul. At LiveTesting he builds the backend, frontend, realtime systems and Appium automation of a real-device testing platform; before that he built enterprise Angular apps at Testinium and Loadium.
