Error handling

suggest change

Basic docs can be found here

app.get('/path/:id(\\d+)', function (req, res, next) { // please note: "next" is passed
    if (req.params.id == 0) // validate param
        return next(new Error('Id is 0')); // go to first Error handler, see below

    // Catch error on sync operation
    var data;
    try {
        data = JSON.parse('not json'); // JSON.parse throws on invalid JSON. It does not read a file.
    } catch (err) {
        return next(err);
    }

    // If some critical error then stop application
    if (!data)
        throw new Error('Something wrong');

    // To attach extra fields, pass a custom error (see Appendix B):
    // next(new MyError('something wrong', arg1, arg2));

    // Finish request by res.render or res.end
    res.status(200).end('OK');
});    

// Order matters: the first matching error handler runs.
app.use(function (err, req, res, next) {
    if (req.method !== 'POST')
        return next(err); // go to error handler 2

    console.log(req.url, err.message);

    if (req.xhr)
        res.status(err.status || 500).json({ message: err.message });
    else
        res.status(err.status || 500).render('error', { error: err.message });
});

// Error handler 2
app.use(function (err, req, res, next) {
    if (err instanceof MyError) {
        console.log(err.message, err.arg1, err.arg2);
    }
    res.status(err.status || 500).end();
});

Appendix A

// "In Express, 404 responses are not the result of an error, 
// so the error-handler middleware will not capture them." 
// You can change it.
app.use(function(req, res, next) {
    next(new Error(404)); 
});

Appendix B

// How to define custom error
var util = require('util');
...
function MyError(message, arg1, arg2) {
    this.message = message;
    this.arg1 = arg1;
    this.arg2 = arg2;
    Error.captureStackTrace(this, MyError);
}
util.inherits(MyError, Error);
MyError.prototype.name = 'MyError';

Feedback about page:

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



Table Of Contents