Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js with Express - throw Error vs next(error)

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?

like image 296
Alexander Mills Avatar asked Jan 06 '15 08:01

Alexander Mills


People also ask

What is next with error in Express?

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.

How do you handle errors in express JS?

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.

What does next () do in Express?

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.


1 Answers

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

like image 167
Arjun Avatar answered Sep 23 '22 04:09

Arjun