0

I have node 7.8.0 and I have read Node.js Best Practice Exception Handling

Still I can't seem to understand error handling in node.js.

For my http I have

server.on('error', () => console.log('Here I should be replacing
the Error console.'));

For 404 I have this code

app.use((req, res, next) => {
  let err = new Error('Not Found');
  err.status = 404;
  next(err);
});
app.use((err, req, res) => {
  res.status(err.status);
  res.render('error');
});

404 is being caught, it creates the Error object and then it's handled by rendering the error view correctly as I want. But it also throws error log to my console and I have no idea where that is coming from and how to stop it.

I would like to use my own error handling and never actually write errors like 404 into the console.

Codes that I tried and don't seem to work.

var server = http.createServer(app);
const onError = () => console.log('Here I should be replacing the Error console.');
server.on('error', onError);
server.on('uncaughtException', onError);
process.on('uncaughtException', onError);
Community
  • 1
  • 1
Ragnar
  • 4,292
  • 4
  • 31
  • 41

2 Answers2

0

This is due to expressjs. Expressjs if the env is not equal to the test, the all errors writes to the console.

function logerror(err) {
  if (this.get('env') !== 'test') console.error(err.stack || err.toString());
}

Also http.Server does not have an event named error.

Ahmet ATAR
  • 36
  • 4
  • you were right, if I set the environment to test it works. But if I set it to production it still send the error to console. Is there a way how I can force it not to do that for any environment bud development? – Ragnar Apr 04 '17 at 02:31
0

I'm not sure how it can render the error view, given that error handlers require 4 arguments while you're passing it only 3. This is how Express can distinguish error handlers from normal route handlers (documented here).

Try this instead:

app.use((err, req, res, next) => {
  res.status(err.status);
  res.render('error');
});
robertklep
  • 198,204
  • 35
  • 394
  • 381