6

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.

2 Answers 2

10

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

Sign up to request clarification or add additional context in comments.

Comments

4

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.