Vladimir37
Vladimir37

Reputation: 568

Express does not render error

I have this:

//public source
app.use('/src', express.static(__dirname + '/../client/source'));

//Errors
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});
app.use(function(err, req, res) {
    res.status(err.status || 500);
    res.end('ERROR 404!');
});

When server not finding file, created an error is generated and assigned status 404 and error transmitted to next function. Then next function render phrase ERROR 404!. But in practice this does not work. On error server return to browser phrase Error: Not found and stacktrace, pointing to a line with var err = new Error('Not Found');. res.end get no result. What is the problem?

Upvotes: 0

Views: 81

Answers (1)

Renato Gama
Renato Gama

Reputation: 16599

Your error handling middleware must have arity of 4;

app.use(function(err, req, res, next) { // this line
    res.status(err.status || 500);
    res.end('ERROR 404!');
});

Have a look at the docs:

An error-handling middleware has an arity of 4, which must always be maintained to be identified as an error-handling middleware. Even if you don’t need to use the next object, make sure specify it to maintain the signature, else it will be interpreted as a regular middleware, and fail to handle errors.

Upvotes: 2

Related Questions