bugventure
bugventure

Reputation: 498

How to trigger router error handler instead of default error handler in expressjs

My express app uses the default JSON body parser:

app.use(bodyParser.json());

Further down the app.js file I have my own router for building REST API routes:

var api = require('./routes/api/index');
...
app.use('/api', api);

This router has an error handler, among other things:

router.use(function (err, req, res, next) {
  debugger;
  res.status(err.code ? getParseErrorStatus(err.code) : res.status || 500).send({
    error: err.message
  });
});

Whenever the bodyParser throws an error while parsing the request body, I get my generic express error handler called:

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function (err, req, res, next) {
    debugger;
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

This holds true even for calls to /api/* URLs that are caught by the API router.

Instead of always calling the generic error handler, how can I make JSON parsing errors (caught by middleware up in the chain) call the error handler I've defined in the API router, if the URL is an API URL?

Upvotes: 1

Views: 686

Answers (1)

mscdex
mscdex

Reputation: 106698

Error handlers are called at the same router stack level. Since the bodyParser.json() is executed at the main/root/app layer, it will look for the first error handler at the main/root/app layer.

So if you want to handle API body parsing errors, you will have to move your bodyParser.json() middleware to each of your routes/routers that require body parsing.

Upvotes: 4

Related Questions