Back to all snippets
Library/Node.js/API Error Handler
typescriptintermediateexpresserror-handlingapi

How to implement API Error Handler in Typescript

Express error handling middleware

Quick Answer

Create a custom `ApiError` class and a four-argument Express middleware `(err, req, res, next)` to catch all errors and return a consistent JSON shape.

Code Snippet

1import { Request, Response, NextFunction } from 'express';
2
3class ApiError extends Error {
4  statusCode: number;
5
6  constructor(statusCode: number, message: string) {
7    super(message);
8    this.statusCode = statusCode;
9  }
10}
11
12const errorHandler = (
13  err: Error,
14  req: Request,
15  res: Response,
16  next: NextFunction
17) => {
18  if (err instanceof ApiError) {
19    return res.status(err.statusCode).json({ error: err.message });
20  }
21
22  console.error(err);
23  res.status(500).json({ error: 'Internal server error' });
24};
25
26export { ApiError, errorHandler };

What is API Error Handler?

Express error-handling middleware is a four-argument function (err, req, res, next) registered after all routes. This pattern combines a custom ApiError class for intentional errors with a catch-all handler for unexpected ones, returning consistent JSON responses that API consumers can reliably parse.

How It Works

  1. 1Extend `Error` with a `statusCode` property to create `ApiError`.
  2. 2Throw `new ApiError(404, 'Not found')` inside any route handler or middleware.
  3. 3Register the error middleware **after** all routes with `app.use(errorHandler)`.
  4. 4Express detects it is error middleware via the four-argument signature and calls it whenever `next(err)` is invoked.

Common Use Cases

  • REST APIs - Return consistent JSON error shapes across all endpoints
  • Auth errors - Throw 401/403 ApiErrors from middleware
  • Validation errors - Convert validation failures into 400 responses
  • Database errors - Catch and translate DB errors into safe API responses

Key Benefits

  • Centralises all error handling in one place
  • ApiError class separates intentional errors from unexpected ones
  • Consistent JSON error format makes client error handling predictable
  • Prevents stack traces leaking to API consumers in production

Common Mistakes to Avoid

  • Registering the error middleware before routes — Express calls middleware in order, so errors thrown in routes will not reach it.
  • Forgetting the fourth `next` parameter — without it Express does not treat the function as error middleware.
  • Sending the error stack to the client in production — always log it server-side only.

Quick Tips

  • Click the "Copy" button above to copy the code to your clipboard
  • This code is production-ready and can be used in your projects immediately
  • Check out related snippets below for more typescript examples

Frequently Asked Questions

Why does Express error middleware need four parameters?

Express identifies error-handling middleware by checking the function's `length` property. It must be exactly 4 (`err, req, res, next`) for Express to route errors to it instead of treating it as a regular middleware.

About This Typescript Code Snippet

This free typescript code snippet for api error handler is production-ready and copy-paste friendly. Whether you are building a web app, API, or frontend interface, this intermediate-level example will help you implement api error handler quickly and correctly.

All snippets in the Snippetly library follow typescript best practices and are tested for real-world use. You can adapt this code to work with React, Vue, Node.js, or any project that uses typescript.

Tags: express, error-handling, api  | Language: typescript  | Difficulty: intermediate  | Category: Node.js

Build Your Own Snippet Library

Organise your team's code snippets with Snippetly. Share knowledge and boost productivity across your organisation.