views:

189

answers:

2

Hey,

I'm developing a project using Node.js at the backed, with that I'm also using JSON to pass data to and from clients over web sockets. The problem I have is that if an invalid string was sent to the server (easily done by the user messing with the JavaScript console) then it would crash the server while trying to parse it.

The current method I have in place for preventing this occurrence is using a try/catch statement.

My question is, is there a more proper way of checking if a string is parsable? Also, is the use of try/catch statements good practice or are they meant only for debugging?

Thank-you.

+1  A: 

Use of try/catch is essential for creating robust code in many environments - very important to gracefully handle error conditions.

However, whenever you accept data from an external source you must validate it to ensure you haven't opened up a vector of attack.

This node module has a couple of JSON elements including JSON Schema which might be of help: http://github.com/kriszyp/commonjs-utils

Toby Hede
+3  A: 

The above answer is good. But you should also set a listener for uncaught exceptions in node.js. That way you can log exceptions and your server will keep running.

http://nodejs.org/api.html#event-uncaughtexception-54

Marco