express throw error code example

Example 1: node js throw error

FactoryController.prototype.create = function (callback) {
    //The throw is working, and the exception is returned.
    throw new Error('An error occurred'); //outside callback 
    try {
        this.check(function (check_result) {
            callback(check_result);
        });
    } catch (ex) {
        throw new Error(ex.toString());
    }
}

FactoryController.prototype.create = function (callback) {
    try {
        this.check(function (check_result) {
            //The throw is not working on this case to return the exception to the caller(parent)
            throw new Error('An error occurred'); //inside callback 
        });
    } catch (ex) {
        throw new Error(ex.toString());
    }
}

Example 2: express error handling

app.use(function (err, req, res, next) {
  console.error(err.stack)
  res.status(500).send('Something broke!')
})

Example 3: express generator error handling

app.get('/', function (req, res) {
  throw new Error('BROKEN') // Express will catch this on its own.
})