简体   繁体   中英

JS runtime errors in Express

I have a basic Express app which has a few routes.

One is as such:

router.post('/upload', (req, res) => {
  let audioFile = req.files.audioFile;

  const file = __dirname + '/../' + req.body.uploadLocation + audioFile.name;

  mp3.mv(file, function(err) {  // <--- HERE
    if (err) {
      return res.status(500).send(err);
    }

    res.send('File uploaded!');
  });
});

Now, if you would try to upload a file to this route you would get a 500 and that's it. The highlighted line is a result of me changing variable name. Is there any way to get it so that it prints out the actual error? I am tripped up by this so often and it would make it an awful lot quicker if the terminal output just told me the normal JS error like it does on the browser or when I'm running node normally.

In Express there is middleware to handle errors. In the a base setup of express you'll find:

// error handler
app.use(function(err, req, res, next) {
  ...
  // render the error page
  res.status(err.status || 500);
  res.json({ error: err });
});

Just add a console.error there:

// error handler
app.use(function(err, req, res, next) {
  console.error(err.stack); // <- HERE
  ...
  // render the error page
  res.status(err.status || 500);
  res.json({ 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