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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With