javascript
51 lines · 8 steps
Centralized error handling in Express
A custom error class plus a catch-all middleware turn scattered failures into consistent, well-logged JSON responses.
Explained by
highlit
1const logger = require('./logger');
2
3class AppError extends Error {
4 constructor(message, statusCode = 500, details = null) {
5 super(message);
6 this.statusCode = statusCode;
7 this.details = details;
8 this.isOperational = true;
9 Error.captureStackTrace(this, this.constructor);
10 }
11}
12
13function notFoundHandler(req, res, next) {
14 next(new AppError(`Route ${req.method} ${req.originalUrl} not found`, 404));
15}
16
17function errorHandler(err, req, res, next) {
18 if (res.headersSent) {
19 return next(err);
20 }
21
22 let statusCode = err.statusCode || 500;
23 let message = err.message || 'Internal Server Error';
24
25 if (err.name === 'ValidationError') {
26 statusCode = 422;
27 } else if (err.name === 'JsonWebTokenError' || err.name === 'TokenExpiredError') {
28 statusCode = 401;
29 message = 'Invalid or expired token';
30 } else if (err.code === '23505') {
31 statusCode = 409;
32 message = 'Resource already exists';
33 }
34
35 const meta = { method: req.method, path: req.originalUrl, statusCode };
36 if (statusCode >= 500) {
37 logger.error({ ...meta, stack: err.stack }, message);
38 } else {
39 logger.warn(meta, message);
40 }
41
42 res.status(statusCode).json({
43 error: {
44 message,
45 ...(err.details ? { details: err.details } : {}),
46 ...(process.env.NODE_ENV === 'development' ? { stack: err.stack } : {}),
47 },
48 });
49}
50
51module.exports = { AppError, notFoundHandler, errorHandler };
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A single error-handling middleware keeps status-code and response shape logic in one auditable place.
- 2Distinguishing operational errors and mapping library error signatures to HTTP codes prevents leaking raw internals to clients.
- 3Logging severity and response detail should scale with status code and environment to aid debugging without exposing stack traces in production.
Related explainers
javascript
import { NextResponse } from 'next/server' const UPSTREAM = 'https://api.exchangerate.host/latest'
A cached exchange-rate proxy in Next.js
route-handler
caching
revalidation
Intermediate
7 steps
typescript
type Event = Record<string, unknown>; interface BatcherOptions { endpoint: string;
Batching analytics events in TypeScript
batching
buffering
async
Intermediate
8 steps
go
package middleware import ( "compress/gzip"
How gzip response compression works in Gin
middleware
compression
http
Intermediate
8 steps
php
<?php namespace App\Services;
Resilient HTTP retries with Laravel's client
http-client
retry-logic
error-handling
Intermediate
7 steps
rust
use std::fs::File; use std::io::{self, BufWriter}; use std::path::Path;
Serializing config to JSON in Rust
serialization
serde
file-io
Intermediate
7 steps
javascript
const formatters = new Map(); function getFormatter(locale, currency) { const key = `${locale}:${currency}`;
Caching Intl.NumberFormat for currency formatting
memoization
internationalization
caching
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/centralized-error-handling-in-express-explained-javascript-cbdb/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.