3

I am new to node and what I would call, real server-side programming (vs PHP). I was setting up a user database with MongoDB, Mongoose and a simple mongoose user plugin that came with a schema and password stuff to use. You can add validation to Mongoose for your fields like so

schema.path('email').validate(function (email) {
    if (this.skipValidation) return true
    return email.trim().length
  }, 'Please provide a valid email')

(this is not my code). I noticed though when I passed an invalid or blank email, .trim() failed and the entire server crashed. This is very worrisome to me because things like this don't happen in your good ol' WAMP stack. If you have a bug, 99.9% of the time it's just the browser that is affected.

Now that I am delving into lower level programming, do I have to be paranoid about every incoming variable to a simple function? Is there a tried-and-true error system I should follow?

forty2011111
  • 115
  • 7

4 Answers4

2

Just check before using the variable with trim, if it is !null for example:

if(!email) {
    return false;
}

And if you want to run your app forever, rather use PM2. If you are interested in running forever, read this interesting post http://devo.ps/blog/goodbye-node-forever-hello-pm2/

Jannis Lehmann
  • 1,428
  • 3
  • 17
  • 31
1

You may consider using forever to keep your node.js program running. Even it crashes, it restarts automatically and the error is logged as well.

Note: Although you could actually catch all exceptions to prevent the node.js from crashing, it is not recommended.

Alex Lau
  • 1,687
  • 10
  • 17
1

One of our strategies is to make use of Node.js Domain to handle errors - http://nodejs.org/api/domain.html

manojlds
  • 290,304
  • 63
  • 469
  • 417
0

You should set up a error logging node modules like Winston, once configured produces useful error/exceptions.

Have a look in this answer for how to catch error within your node implementation, though specific to expressjs but relevant.

Once you catch exceptions, it prevents unexpected crashes.

Community
  • 1
  • 1
Palak Bhansali
  • 731
  • 4
  • 10