Proper way to handle errors in ExpressJS 3 - node.js

I've been struggling for the past hours trying to find a decent tutorial on how to handle errors for a NodeJS + ExpressJS 3 api.
I've read a lot of questions/answers on SO and read the official ExpressJS guide and still cannot figure out the proper way to do such an important thing. Most of the answers I found were relevant in Express 1 or Express 2, but are not anymore and the ExpressJS Guide just describes something out of context, which makes it really hard to understand.
So here's my use case : I want to get informations about a city, using the GET /cities/:slug. If the slug doesn't exist or an error happened (with MongoDB or Mongoose for example), I want to return an error code.
Here's the relevant part of my current code :
if (err || !city) {
res.json({code:500, city:[]});
}
It's a basic example and it's working "well", but I'm pretty sure that's not the right way to do it in NodeJS.
Also, this does not stop my NodeJS instance, but some unexpected errors might. From what I read, this is not a problem in production because apparently restarting the NodeJS instance is cleaner, and third-parties handle it pretty well (read about Cluster, Forever or even Monit).
Would love to have more insights on this problem I've been overlooking for too long.

Related

Deployed Node.js application to bluemix, error : cannot find concept-insights-devoxx.mybluemix.net/css/style.css

The style.css lives in public/css folder and config/express.js has
app.use(express.static(__dirname + '/../public'));
Still I am getting the following error
Please help , Thanks, Sandhya
I don't think your missing css is the problem. It would just mess up your styling on the page.
The TypeError above that seems more to the point. An object property "offsetTop" was referred to, but the object doesn't actually exist (or something that was supposed to create it, didn't return anything).
I'd guess that might have been what caused the 502 error, or perhaps the other way around (i.e. a proper response could not be received from the api call, and for some reason that case was not considered by whoever wrote the logic that comes after that).
Do you have the relevant code that you could post perhaps?
Thanks for the answer! The problem was in manifest.yml, where I was binding to a different instance of Concept Insights service. Therefore, the credentials given in app.js for the instance of Concept Insights populated with my corpus were getting overwritten.
Thanks for looking at this issue !
Sandhya

sentry: setUserContext in nodejs with raven-node?

I've tried to get the setUserContext function with raven-node in my nodejs app, but I cannot find how to set the user context. Has anyone made it work?
I was able to make it work in the client-side, with "Raven.setUserContext" but not in the nodejs backend :(
User context isn't implemented in raven-node: https://github.com/getsentry/raven-node/issues/134
I'm a contributor to the project, and it's my number one priority to have this done shortly – should be a matter of days.
Edit – we just published raven-node 0.10.0 which adds setUserContext.

Globle error filter in node js

I am working on node from last 2-3 months on a project. Now I want to handle errors from a single point in node. For example : I have several api functions in my project. Many of them are taking _id as an api input. I need to parse this id using mongoose objectid before using in query. Now if the format of _id is not valid, it will throw the casting error. It could be handled by mongoose object isvalid property. But my purpose is that, at any place if it is not handled in code I want to catch the error and log it to my log file and send a common message like 'error occurs' to the UI. I want to add a common error handler for all the api that do the logging and error handling for my api, like we use .net MVC - error handler filer through the application.
I have tried using domain. But in domain.on('error',func(err){}); it is not working. I put my api functions call in domain.run();
If any body have any suggestion for me, please let me know.
Take a look at the domain module, if your app powered by express you can use the package - express-domain-middleware

How to handle Node js app errors to prevent crashing

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?
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/
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.
One of our strategies is to make use of Node.js Domain to handle errors - http://nodejs.org/api/domain.html
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.

JavascriptMVC route examples

I am staring out with JavascriptMVC, and currently trying to figure out jQuery.route. I know there are other 3rd party plugins that perform routing, but I'm specifically trying to figure out jQuery.route which comes with Javascript MVC.
I'm familiar with Backbone.js and Ember's routing frameworks, but I just don't understand JMVCs. I've tried reading the documentation and looking at the code here, but there are no examples and still can't figure it out.
I'm trying to do something basic such as, if the browser sees a URL like
http://localhost/helloWorld#state1
then some function will be executed. Something similar to how Backbone and Ember work. Can this be done using JavascriptMVC's jQuery.route?
I think deparam should work for the task of figuring out the route for the current page:
var currentRoute = $.route.deparam(window.location.current);
if (currentRoute == "state1") {
// handle route
}

Resources