如何使用Begin Rescue 处理Ruby中的错误

分享于 

2分钟阅读

Rails

  繁體

捕获错误

Ruby具有一些内置的方式,这些方式可以让你捕获错误并在正常崩溃时保持代码运行,


def crappy_method
 begin
 # Code that is likely to break
 rescue Exception => e # Creates a new instance of Exception and saves it as variable e
 # What to do when the code breaks
 e.message # Returns a string of the error
 e.backtrace # Returns the stack trace of the error
 # You can even add some code that will alter the result of the begin block and then call
 retry
 else
 # This runs only when no exception was raised
 ensure
 # This runs whatever happens
 end
end


基本上,将你认为有可能中断的代码在begin和rescue之间放入,每当代码中断时,都会调用rescue下面的部分,这使你可以"保存"正在处理的内容。

备注: 虽然ensure代码中运行的最后一个块,但是它不是返回值!

下面是我在生产代码中使用它的示例;


def find_xml_gz_sitemap # Checks for /sitemap.xml.gz
 puts 'No sitemap found on /sitemap or /sitemap.xml, trying sitemap.xml.gz'; write('Searching sitemap.xml.gz', 'message', 1)
 begin
 link = Timeout.timeout(10) { open("#{@site}sitemap.xml.gz", allow_redirections: :all, read_timeout: 10) }
 gz = Zlib::GzipReader.new(link)
 xml = gz.read
 @links = Nokogiri::XML.parse(xml).search('*//loc').map(&:inner_html)
 puts 'Sitemap.gz found!'; write('Sitemap found!', 'message', 1)
 has_nested_sitemap?
 rescue
 write('No sitemap :(', 'message', 1); find_robots_txt_sitemap
 end
 end


errors  拯救  
相关文章