How to manage HTTP errors in Node.js

Hi I'm developing my first Node.js application and I found my first issue in something really basic, I can't catch the HTTP errors (404, 500, ...)

I've followed the doc (I think so) but I suppose that I'm missing something.

This is my code:

var express = require('express')
app = express()
app.use(express.logger('dev'));

app.get('/', function(req, res) {
    res.send('Hellow World!!!')
})
app.use(app.router);
app.use(function(err, req, res, next) {
    console.error('Oh!! ERROR');
    console.error('My ERROR: ' + JSON.stringify(err));
});

app.listen(3000);
console.log('Server running at http://127.0.0.1:3000/');

Thanks in advance.

So the way express works is if it hits the end of the entire stack of middleware and route handlers and nothing has responded yet, it's going to send the fallback 404 response automatically without raising an error. This is why your error handling middleware isn't being called. By default, express doesn't consider a 404 an error, which is probably the right way to think of it.

If you want to customize this, you can put a middleware at the end of your stack to either serve a custom 404 page directly or call next with an error if you prefer that way.

app.get('/'...
app.get('/two'...
app.get(/'three'...

app.use(middleware1...
app.use(middleware2...
app.use(app.router);
app.use(function (req, res, next) {
    //Option 1: respond here
    return res.status(404).render('my_404_view');
    //Option 2: trigger error handler
    return next(new Error('404ed!'));
}

Option 2 will trigger your error handling middleware. There you will have to get info from the error object to determine the desired view to render and status code to send. I personally define an errors.NotFound class that has a 404 code and lets me render a friendly 404 page view.