Can someone expound on the times when it's appropriate in a node.js Express app to throw an error like so:
throw new Error('my error');
or to pass this error on via the callback usually labelled 'next' like so:
next(error);
and could you please explain what each of them will do in the context of an Express app?
for example, here is an express function dealing with URL parameters:
app.param('lineup_id', function (req, res, next, lineup_id) { // typically we might sanity check that user_id is of the right format if (lineup_id == null) { console.log('null lineup_id'); req.lineup = null; return next(new Error("lineup_id is null")); } var user_id = app.getMainUser()._id; var Lineup = app.mongooseModels.LineupModel.getNewLineup(app.system_db(), user_id); Lineup.findById(lineup_id, function (err, lineup) { if (err) { return next(err); } if (!lineup) { console.log('no lineup matched'); return next(new Error("no lineup matched")); } req.lineup = lineup; return next(); }); });
In the line commented "//should I create my own error here?" I could used "throw new Error('xyz')", but what exactly would that do? Why is it usually better to pass the error to the callback 'next'?
Another question is - how do I get "throw new Error('xyz')" to show up in the console as well as the browser when I am in development?
send(user) }) If getUserById throws an error or rejects, next will be called with either the thrown error or the rejected value. If no rejected value is provided, next will be called with a default Error object provided by the Express router.
The simplest way of handling errors in Express applications is by putting the error handling logic in the individual route handler functions. We can either check for specific error conditions or use a try-catch block for intercepting the error condition before invoking the logic for handling the error.
The next function is a function in the Express router which, when invoked, executes the middleware succeeding the current middleware. Middleware functions can perform the following tasks: Execute any code.
In general express follows the way of passing errors rather than throwing it, for any errors in the program you can pass the error object to 'next' , also an error handler need to be defined so that all the errors passed to next can be handled properly
http://expressjs.com/guide/error-handling.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With