Error handling in Express

suggest change

Express can use one error-handling middleware for errors passed with next(err). Define that handler after the other routes. It must have four parameters, or Express will not treat it as an error handler.

Example

var express = require('express');
var app = express();

//GET /names/john
app.get('/names/:name', function(req, res, next){
    if (req.params.name == 'john'){
        return res.send('Valid Name');
    } else{
        next(new Error('Not valid name'));    //pass to error handler
    }
});

//error handler
app.use(function(err, req, res, next){
    console.log(err.stack);
    return res.status(500).send('Internal Server Error');
});

app.listen(3000);

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents