dsp_099
dsp_099

Reputation: 6121

Why is using try / catch a bad idea in this scenario?

I've been working on hooking up mongoDB to a node.js server. I've got the code all neatly put away, however it takes about 5~ seconds to connect, and if a request for an insert or a query comes before that, the server will crash.

My first instinct was to use try/catch to filter off any requests which error out. I will want the server to go on regardless of what errors an individual request breaks, so why not use it?

Everywhere I look it's touted as a bad idea, I'm not sure I understand why.

Upvotes: 0

Views: 152

Answers (1)

Brad
Brad

Reputation: 163262

A try/catch block around something that simply ignores the error is generally considered bad practice. However, if that is the behavior you want, then there is nothing wrong with it. Just consider that it may not actually be the best behavior. You may, at a minimum, want to log the fact that an exception occurred.

Now, due to the asynchronous nature of Node.js, try/catch blocks are sometimes not useful. I don't know what part of the MongoDB API you are using, but if there is a callback, you will want to instead check the err parameter, which should be the first parameter of your callback function in most cases.

Finally, for all of my applications, I connect to any necessary DBs synchronously, and start listening on ports afterwards. But, this is only relevant if a persistent connection makes sense for your project. Plus, you still have to watch for errors, which can occur as connection failures do happen.

Upvotes: 3

Related Questions