How can I catch a bodyParser error in a router's errorHandler in express.js 4?
Example code:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
// use bodyParser.json()
app.use(bodyParser.json());
// setup route /test
var testRouter = express.Router();
testRouter.post('/', function(req, res, next) {
next(new Error('not implemented'));
});
testRouter.use('/', function(err, req, res, next) {
res.send('testRouter error: ' + err.message);
});
app.use('/test', testRouter);
// default error handler
app.use(function(err, req, res, next) {
res.send('default error handler: ' + err.message);
});
module.exports = app;
Sending a POST
request to /test
with an empty body will return testRouter error: not implemented
. This message comes from the error handler which is defined in the testRouter
, and this is what I expect to happen.
Sending a POST
request to /test
with a malformed json body, however, will return default error handler: [bodyParser error]
. This message comes from the default error handler.
I want the error handler in the testRouter
to handle all bodyParser errors that occur on requests to /test
. How can I achieve that?
You need to have
testRouter
use the body parser middleware:Otherwise the default router will handle the error, like you noticed.
If you also want to use the body parser middleware for the default router, make sure that you declare it after you added
testRouter
: