Skip to content

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

@saitodeveloper

Description

@saitodeveloper

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!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions