Reputation: 270
How do I go about specifying the error code with a return next(err) statement so that I can display it in my catch all middleware?
var express = require('express');
var exphbs = require('express-handlebars');
var fs = require("fs");
var app = express();
app.engine('handlebars', exphbs({defaultLayout: 'main'}));
app.set('view engine', 'handlebars');
app.get('/', function(req, res, next) {
// simulate 404 error
fs.readFile("foo.txt", "utf8", function(error, data) {
if(error) {
next(new Error('Aiiii caramba'));
}
});
});
/* Error Handling (gotta catch 'em all) */
app.use(function(err, req, res, next) {
res.status(err.status || 500)
.render('error', {
status: req.status,
error: err
});
});
app.listen(3000, function() {
console.log('Listening...');
})
The Error object doesn't acccept an argument for error code. I also tried setting the response status before returning next... to no avail.
res.status(404); return next(err);
No matter what I do, I get error 500.
Thank you in advance for your time.
Upvotes: 3
Views: 1253
Reputation: 3180
There's no reason why Error
should have a status
property. If you want it, you have to craft your own error and let it inherit from Error
.
In ES6 this can be done as follows:
class NotFound extends Error {
constructor(message) {
super(message);
this.status = 404;
}
}
If you are stuck with ES5, you can instead use the util
module provided with node:
var util = require('util');
function NotFound(message) {
Error.call(this);
this.message = message;
this.status = 404;
}
util.inherits(NotFound, Error);
Now, you can throw your custom error as next(new NotFound('Aiiii caramba'));
. Arguably, NotFound('Aiiii caramba')
expresses in a clear way the kind of encountered error.
Upvotes: 3
Reputation: 12953
the problem is with your error handling after the middlewares:
/* Error Handling (gotta catch 'em all) */
app.use(function(err, req, res, next) {
res.status(err.status || 500)
.render('error', {
status: req.status,
error: err
});
});
you have there the line: res.status(err.status || 500)
and since your error object does not have a status field, it is always assigned to 500
Upvotes: 1