expressjs / expressjs/body-parser
Suggestion: Add option to customize or transform `body-parser` errors before they reach the Express error handler
- Dominant language
- JavaScript
- Stars
- 5.5k
- Forks
- 767
- Avg merge
- 13h 53m
- Merged PRs (30d)
- 10
Description
## 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](https://github.com/expressjs/body-parser/blob/168afff3470302aa28050a8ae6681fa1fdaf71a2/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:
```js
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!
Contributor guide
Assessment
This issue has not been assessed yet.