简体   繁体   中英

Express router print error

I have this router with Express.js:

router.post("/last-update", function(req, res) {
  rules[req.body.route].last_update = req.body.date;
  log.info("Set Last Update " + route + " " + req.body.date);
  res.send({"statusCode": 200});
});

This code will err because route on line 3 is undefined. When I send a POST request to /last-update , the node.js console only logs internal error 500 , without providing stacktrace. Is there a way to enable stack trace?

The easiest way is to create a "catch all" after all your routes are defined. If you already have one just log the error here.

app.use(function (err, req, res, next) {
    res.status(err.status || 500);
    res.send('error');
    console.log(err);
});

Find where the error gets logged and add this:

console.log(err.stack, 'stack');

Tip, use Express Generator to generate an example application where you will see some examples on how to catch and extract error information:

app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM