generator icon indicating copy to clipboard operation
generator copied to clipboard

npx express-generator does not follow error recommendations

Open sdavids opened this issue 6 years ago • 3 comments

https://expressjs.com/en/guide/error-handling.html#the-default-error-handler

So when you add a custom error handler, you must delegate to the default Express error handler, when the headers have already been sent to the client

function errorHandler (err, req, res, next) {
  if (res.headersSent) {
    return next(err)
  }
  res.status(500)
  res.render('error', { error: err })
}

The express-generator does not follow the recommendation:

$ npx express-generator
$ grep -A 10 '// error handler' app.js
// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

sdavids avatar Mar 10 '20 13:03 sdavids

I think this may be a documentation issue on the website; there is no requirement to delegate to the default handler if the headers have already been sent; users can do whatever logic they would like to do.

dougwilson avatar Mar 10 '20 13:03 dougwilson

from the docs:

If you call next() with an error after you have started writing the response (for example, if you encounter an error while streaming the response to the client) the Express default error handler closes the connection and fails the request.

barraponto avatar Jun 13 '20 01:06 barraponto

@sdavids Did you create the error handler after all the other routes. That could cause some issues if you didn't.

oviecodes avatar Nov 08 '20 13:11 oviecodes