Rails: Exceptions vs conditional statements
I have a Rails application that queries a 3rd party web servi开发者_如何学运维ce. I am trying to decide how to handle an invalid response (e.g. service unavailable).
The two options I am considering are:
1) WebService returns nil on error
response = WebService.query
if response
# Query was successful
else
# Invalid response
end
2) WebService raises an exception on error
begin
response = WebService.query
rescue
# Invalid response
end
# Query was successful
What are the advantages and disadvantages of each approach? Which one is "the Rails way"?
Many thanks.
Conditional statements are usually faster than exceptions. See How slow are (Ruby) Exceptions?
The point is that Exceptions and conditional statements have different meaning. You use exceptions when you don't expect something to fail and when an error occurs is an exceptional event. On the opposite, conditional statements control a flow. This is the same concept expressed in this post from Thoughtbot.
精彩评论