Mongoose error handling in one place Mongoose error handling in one place mongoose mongoose

Mongoose error handling in one place


It is standard in Node for error events to provide one argument, which is the error itself. In my experience, even the few libraries that provide additional parameters always leave the error as the first, so that you can use a function with the signature function(err).

You can also check out the source on GitHub; here's the pre-save hook that emits an error event, with the error as an argument, when something goes awry: https://github.com/LearnBoost/mongoose/blob/cd8e0ab/lib/document.js#L1140

There is also a pretty easy way in JavaScript to see all the arguments passed to a function:

f = ->  console.log(arguments)f()                     # {}f(1, "two", {num: 3})   # { '0': 1, '1': 'two', '2': { num: 3 } }f([1, "two", {num: 3}]) # { '0': [ 1, 'two', { num: 3 } ] }

So now to the part where your function isn't working; how exactly does your code read? The name handleError isn't special in any way; you'll need one of these two:

Option 1: define the function, and pass a reference into the event registration:

handleError = (err) ->  console.log "Got an error", errProduct.on('error', handleError)

Option 2: define the function inline:

Product.on 'error', (err) ->  console.log "Got an error", err


Spent 1 hour finding the easy, common place & best way to do it:

Below code is in express.js:

In the app.js:

// catch 404 and forward to error handlerapp.use(function (req, res, next) {  next(createError(404));});// error handlerapp.use(function (err, req, res, next) {  // set locals, only providing error in development  if (req.app.get('env') === 'development') {    res.locals.message = err.message;    res.locals.error = err;    console.error(err);  } else {    res.locals.message = 'Something went wrong. Please try again!';    res.locals.error = {};  }  // render the error page  res.status(err.status || 500);  res.render('error');});

In the product-controller.js:

let handleSuccess = (req, res, next, msg) => {  res.send(msg + ' success ');};let handleError = (req, res, next, msg, err) => {  // Create an error and pass it to the next function  next(new Error(msg + ' error ' + (err.message || '')));};

We could also put the above generic code in a common file, and import the file, to reuse the above functions in other controllers or any other file.