Attempt to parse JSON without crashing Node.js server
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.
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/process.html#process_event_uncaughtexception
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: https://github.com/kriszyp/json-schema
精彩评论