Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 545
Ryan Avatar asked Aug 22 '10 06:08

Ryan


2 Answers

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

like image 130
Marco Avatar answered Oct 05 '22 23:10

Marco


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

like image 39
Toby Hede Avatar answered Oct 05 '22 22:10

Toby Hede