For example, below, is the code bit am using to catch 404s and create a JSON error response that I'll later send out with the error stack merged with a few other details:
// catch 404 and forward to error handle
app.use((req, res, next) => {
const err = new Error('Not Found');
err.request = req.originalUrl;
err.status = 404;
next(err);
});
// error handlers
app.use((err, req, res) => {
console.log('ERROR PASSING THROUGH', err.message);
// get the error stack
const stack = err.stack.split(/\n/)
.map(stackTrace => stackTrace.replace(/\s{2,}/g, ' ').trim());
// send out the error as json
res.status(err.status || 500).json({
api: err,
url: req.originalUrl,
error: err.message,
stack,
});
});
When the error is instantiated const err = new Error('Not Found'); it immediately throw this error and err.request = req.originalUrl; is never reached.
This is not the case with the prior version of node I was using v4.2.5
UPDATE: This is when next is used.
// catch 404 and forward to error handler
app.use((req, res) => {
const err = new Error('Not Found');
err.status = 404;
res.status(err.status).json({
status: err.status,
request_url: req.originalUrl,
message: err.message,
stack_trace: err.stack.split(/\n/).map(stackTrace => stackTrace.replace(/\s{2,}/g, ' ').trim()),
});
});
This one works as expected.
Which version of Express?
@hacksparrow Express v4.13.4
This is caused by a misunderstanding of next and the Express middleware stack, let's continue the discussion at https://gitter.im/expressjs/express, where we discuss Express in general and provide support.
For anyone who comes across this issue in the future, the summary from the Gitter conversation was that the issue didn't relate to the version of Node.js, rather the code was trying to define an error handler with only three arguments (err, req, res) but needed to use four (err, req, res, next) in order to actually be an error handler (documentation: http://expressjs.com/en/guide/using-middleware.html#middleware.error-handling).
Most helpful comment
For anyone who comes across this issue in the future, the summary from the Gitter conversation was that the issue didn't relate to the version of Node.js, rather the code was trying to define an error handler with only three arguments (
err, req, res) but needed to use four (err, req, res, next) in order to actually be an error handler (documentation: http://expressjs.com/en/guide/using-middleware.html#middleware.error-handling).