Alexander Kireyev
Alexander Kireyev

Reputation: 10825

Mongoose error handling in one place

I found in mongoose docs that I can handle errors generally, that I want. So you can do like:

Product.on('error', handleError);

But what is the signature of this handleError method? I want something like this:

handleError = (err) ->
  if err
    console.log err
    throw err

But this doesn't work.

Upvotes: 5

Views: 6632

Answers (2)

Manohar Reddy Poreddy
Manohar Reddy Poreddy

Reputation: 27415

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 handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.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.

Upvotes: 0

Michelle Tilley
Michelle Tilley

Reputation: 159105

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", err

Product.on('error', handleError)

Option 2: define the function inline:

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

Upvotes: 5

Related Questions