express icon indicating copy to clipboard operation
express copied to clipboard

404 & 500 Error pages

Open gahula opened this issue 12 years ago • 1 comments

Based on your example I have used the following code to generate 404 or 500 error pages which worked in 3. However for each request the 404 error executes i.e. regardless of the url the 404 function below displays the 404.html page.

How can the 404 and 500 errors be shown in Express 4 ? Would I need to add specific middleware ?

app.use(function(req, res, next){
    res.status(404);

    // respond with html page
    if(req.accepts('html')) {
        res.render('errors/404.html', {error: 'The resource you where looking for is not available.'});
        return;
    };

    // respond with json
    if(req.accepts('json')) {
        res.send({ error: 'The resource you where looking for is not available.' });
        return;
    }
    // default to plain-text. send()
    res.type('txt').send('The resource you where looking for is not available.');
});
app.use(function(err, req, res, next){
    console.log(err);
    // we may use properties of the error object
    // here and next(err) appropriately, or if

    // we possibly recovered from the error, simply next().
    res.status(err.status || 500);

    // respond with html page
    if(req.accepts('html')) {
        res.render('errors/500.html', {error: 'Something is broken on our end, email us if this issue persist.'});
        return;
    }

    // default to plain-text. send()
    res.type('txt').send('Something is broken on our end, email us if this issue persist.');
});

gahula avatar May 30 '14 21:05 gahula

In your express app, those things need to be the very last thing you add, i.e. they should be right above your app.listen()

dougwilson avatar May 30 '14 21:05 dougwilson