3

I have several json objects that come from the server. At the moment, I'm using the browsers' json functionalities (my application only supports modern browsers) to parse json to objects.

Should I be using a try/catch to make my app more robust or would using try/catch create another set of problems?

3 Answers 3

5

try..catch is not a magical construct to make problems go away. The question is, what would you put in your catch { } clause?

If you can do something useful if the json is broken. Something that allows you to make sure that the state of the app is correct again, then it makes sense.

But, what are the chances you will receive broken json? If you're generating and parsing the json yourself, the chances are low.

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

Comments

2

A general rule for using try / catch blocks is, only use if it you 100% know what to do next.

In other words, if you can't continue with your application flow because parsing of JSON objects failed, throw an error or don't use try / catch.

Beside that, you can use json2.js or any other library which shims the native JSON support to also support old'ish browsers.

Comments

1

The validation of the response should be in the SERVER, not on the client side.
So you don't need to worry if the parsing will fail, (unless a programmer failed...)

The client side validations relie on the server side but not the other way around.

5 Comments

that statement doesn't make any sense to me. Its just about parsing json-strings into objects which is a pretty common task.
@jAndy. The json validation should be done on the server side.
maybe I didn't get he question right, but I think its (again) just about parsing json-string on the client, which happens alot. Of course you can argue the you just "expect" those strings to be correct, but I see no problem in carrying about that also clientside since double-quoting key-names is a common error for instance.
@jAndy. You can check if you want to, but you should be able to trust the server. If you want to do double check and willing to get the performance hit, You may.
actually its personal preference. I do sleep better knowing my app will continue to work even if I received bad data and I do handle it properly.

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.