Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 328
zishe Avatar asked Aug 22 '12 04:08

zishe


People also ask

Does Mongoose throw error?

When we run code to save or update the data, all validator runs and if any issue is found by the validator, mongoose throws the error. But these errors are completely different, different validators send errors in different ways.

What is error handling in Express?

Error Handling refers to how Express catches and processes errors that occur both synchronously and asynchronously. Express comes with a default error handler so you don't need to write your own to get started.


1 Answers

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
like image 186
Michelle Tilley Avatar answered Sep 28 '22 04:09

Michelle Tilley