Error handling in Express

suggest change

In Express, you can define unified error handler for handling errors occurred in application. Define then handler at the end of all routes and logic code.

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);    // e.g., Not valid name
    return res.status(500).send('Internal Server Occured');
});

app.listen(3000);

Feedback about page:

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


Web apps with Express:
* Error handling in Express

Table Of Contents
1 npm
2 Web apps with Express
41 cli
43 grunt
59 Hack
64 ES6
67 Redis
69 MongoDB
86 MongoDB
87 Lodash
91 CORS
105 N-API
108 Require