Is it OK to use try – catch blocks as a way of writing failsafe code?


Is it OK to use try – catch blocks as a way of writing failsafe code?

Usually whenever I'm dealing with complex objects or otherwise complicated functions that require have a lot of data flying about it's necessary to perform checks to make sure the types of all the values I'm dealing with are correct.

However at the moment I'm writing a function that deals with some particularly tricky dynamic data and can potentially get called multiple times.

Here is the framework for it as of now:

const getItemMapFromProps = props => { try { const content = props.cachedItem.content || props.item.content; JSON.parse(content).blocks.reduce({ //.... }) } catch(e) { return []; } } 

The problem is that certain points of it calling props.cachedItem.content & props.item.content can be undefined, or they can be defined and not get JSON.parsed properly, or the result of JSON.parse might lack a blocks property. So normally I would check for all of these in the logic directly and structure my code accordingly. But it comes out looking ridiculous and complicated and I feel like using a try { } catch() { } block is so much more of a cleaner and easier way to return a default value if something goes wrong in the function. That being said I don't know how acceptable of a pattern this is. Thoughts/advice?

Submitted July 17, 2017 at 07:49PM by styke
via reddit http://ift.tt/2v96zVV

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s