最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript try catch with json parse - Stack Overflow

programmeradmin7浏览0评论

I have several json objects that e 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?

I have several json objects that e 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?

Share Improve this question edited Apr 27, 2012 at 12:55 gdoron 150k59 gold badges302 silver badges371 bronze badges asked Apr 27, 2012 at 12:42 frenchiefrenchie 52.1k117 gold badges320 silver badges528 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 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.

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.

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.

发布评论

评论列表(0)

  1. 暂无评论