Suggestion: Add option to customize or transform `body-parser` errors before they reach the Express error handler

Aperta
#658 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
5/5
Tempo stimato
Più di una settimana
Idoneità per principianti
35/100
Tipo di issue
Funzionalità
Chiarezza
Abbastanza chiara
Stato di attività
Ferma
Stack tecnologico
express, javascript, node.js
Ambito
api, backend

Direzione di ricerca

Inizia leggendo lib/read.js nel percorso dell’errore indicato per capire come body-parser chiama next(err). Definisci e documenta il callback di trasformazione opzionale proposto, quindi verifica che possa sostituire o modificare gli errori di parsing prima che raggiungano il gestore degli errori di Express, preservando il comportamento esistente quando non viene utilizzato.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

Summary

As a long-term user of Express.js, I’ve often needed to adjust the error type or structure returned by body-parser to fit my project’s internal architecture.
Many teams and companies use their own standardized Error classes with custom fields like error codes, metadata, or log levels.

Currently, this requires wrapping the body-parser middleware to intercept and transform errors before they reach the main Express error handler.

This issue proposes adding an intermediate options function (or callback) that allows developers to modify or replace the error before it’s passed to next().


Motivation

When body-parser encounters an error (for example, a malformed JSON payload), it directly calls next(err) — see lib/read.js#L74.

In large-scale applications or microservice architectures, teams often need to maintain consistent error formats and logging standards.
To achieve that today, we typically wrap the middleware to intercept and modify the error manually — which leads to repetitive boilerplate code.


Example Use Case

Here’s an example of how we currently handle this with a wrapper:

const express = require("express");
const app = express();

const jsonParser = express.json();

const jsonParserDecorator = (req, res, next) => {
  const nextInterceptor = (parameter) => {
    /* Amend the error before it goes to the error handler */
    if (
      parameter instanceof Error &&
      parameter.type === 'entity.parse.failed'
    ) {
      parameter.cd = errorCodes.requestMalformedJson;
      parameter.logLevel = LOG_LEVEL.warn;
    }

    return parameter ? next(parameter) : next();
  };

  jsonParser(req, res, nextInterceptor);
};

app.use(jsonParserDecorator);
Benefits
  • 🧩 Reduces repetitive middleware wrapping.
  • ✨ Offers a clean, expressive way to integrate with custom error architectures.
  • ⚙️ Maintains full backward compatibility (optional feature).
  • 💡 Improves flexibility for enterprise and multi-service Express applications.

Additional Notes

I’m happy to discuss or contribute an initial PR for this feature if it aligns with the maintainers’ goals for the project.

Thanks for considering this suggestion!

Lingua principale
JavaScript
Stelle
5.5k
Fork
802
Merge medio
7h 54m
PR unite (30g)
8

Preparare l'ambiente

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di expressjs/body-parser

Tutte le issue di expressjs/body-parser

Issue simili

Altre issue su JavaScript

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.