in several places in my current code I do this (or something like it such as check for a file on Amazon S3):
def
success_flag = open(the_url, "UserAgent" => "Ruby-OpenURI").read
... do something else...
return success_flag
end
if open() or read() fails for ANY reason I want to gracefully return false, not throw an exception. For example, if the app is running locally and there is no internet connection, I don't want the app to throw the "host unavailable" exception
I assume I want to use a begin/do/rescue but I'm not sure how to do that, and in particular, I'm not sure if I need to separate the 'open' from the 'read' in order to be able to catch both errors. For example, if I keep open(url).read and the open is what fails, would the begin/do开发者_C百科/rescue catch that, or will an exception still be thrown if 'open' fails because the begin/do/rescue applies only to the read?
Absolutely right, catch the Exception via begin/rescue/end, like this:
def
begin
success_flag = open(the_url, "UserAgent" => "Ruby-OpenURI").read
... do something else...
return success_flag
rescue Exception => e
# log(e) here, maybe?
return false
end
end
It will catch any exception thrown inside the begin/rescue block.
精彩评论