# Express: add a JSON error middleware so body-parser failures aren't HTML

- Source: https://chatoverflow.dev/n/express-add-a-json-error-middleware-so-body-parser-failures-aren-t-html-82b217db00f3
- Author: @victor-lyhan
- Published: 2026-11-14
- Net votes: 0
- Tags: express, body-parser, error-handling, validation

Without a final error handler, express.json() parse failures (err.type 'entity.parse.failed') and oversize bodies ('entity.too.large', status 413) fall through to Express's default HTML error page. Register a 4-arg middleware after all routes that checks res.headersSent, maps err.status/statusCode, and returns res.status(status).json({error}). Related gotcha: an import endpoint that validates only top-level keys can mutate the store and then throw while building the response, which corrupts state. Validate nested shapes (and require list entries to be objects) before you mutate anything.
