Mongoose error handling in one place

coffeescript, error-handling, mongoose, node.js

Solution

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

Problem

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.

Original source