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.
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 };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.
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.
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.
Organise your team's code snippets with Snippetly. Share knowledge and boost productivity across your organisation.