我經常發現自己處理這些類型的場景:你可以通過一個代碼塊,返回一個錯誤的方法?
require 'nokogiri'
require "open-uri"
url = "https://www.random_website.com/contains_info_I_want_to_parse"
nokodoc = Nokogiri::HTML(open(url))
# Let's say one of the following line breaks the ruby script
# because the element I'm searching doesn't contain an attribute.
a = nokodoc.search('#element-1').attribute('href').text
b = nokodoc.search('#element-2').attribute('href').text.gsub("a", "A")
c = nokodoc.search('#element-3 h1').attribute('style').text.strip
會發生什麼事,我會創造約30個變量都在尋找在一個頁面不同的元素,我會在循環代碼多個頁面。但是,這些頁面中的一些可能會有一個稍微不同的佈局,並且不會有這些div中的一個。這會破壞我的代碼(因爲你不能在nil上調用.attribute或.gsub)。但我永遠無法猜測到哪條線。 我去到的解決方案通常是圍繞每行:
begin
line #n
rescue
puts "line #n caused an error"
end
我希望能夠做這樣的事情:
url = "https://www.random_website.com/contains_info_I_want_to_parse"
nokodoc = Nokogiri::HTML(open(url))
catch_error(a, nokodoc.search('#element-1').attribute('href').text)
catch_error(b, nokodoc.search('#element-2').attribute('href').text.gsub("a", "A"))
catch_error(c, nokodoc.search('#element-3 h1').attribute('style').text.strip)
def catch_error(variable_name, code)
begin
variable_name = code
rescue
puts "Code in #{variable_name} caused an error"
end
variable_name
end
我知道,把&每個新方法之前工作:
nokodoc.search('#element-1')&.attribute('href')&.text
但是我希望能夠在終端上顯示'puts'的錯誤以查看我的代碼何時發生錯誤。
可能嗎?