我试图能够进行全局异常捕获,以便在发生错误时添加额外信息。我有两个班级,“爬虫”和“亚马逊”。我想要做的是能够调用“crawl”,在amazon中执行一个函数,并在crawl函数中使用异常处理。
这是我的两个课程:
require 'mechanize'
class Crawler
Mechanize.html_parser = Nokogiri::HTML
def initialize
@agent = Mechanize.new
end
def crawl
puts "crawling"
begin
#execute code in Amazon class here?
rescue Exception => e
puts "Exception: #{e.message}"
puts "On url: #{@current_url}"
puts e.backtrace
end
end
def get(url)
@current_url = url
@agent.get(url)
end
end
class Amazon < Crawler
#some code with errors
def stuff
page = get("http://www.amazon.com")
puts page.parser.xpath("//asldkfjasdlkj").first['href']
end
end
a = Amazon.new
a.crawl
有没有办法可以在“crawl”中调用“stuff”,这样我就可以对整个 stuff 函数使用异常处理?有没有更好的方法来实现这一点?
编辑:这是我结束的时候
require 'mechanize'
class Crawler
Mechanize.html_parser = Nokogiri::HTML
def initialize
@agent = Mechanize.new
end
def crawl
yield
rescue Exception => e
puts "Exception: #{e.message}"
puts "On url: #{@current_url}"
puts e.backtrace
end
def get(url)
@current_url = url
@agent.get(url)
end
end
c = Crawler.new
c.crawl do
page = c.get("http://www.amazon.com")
puts page.parser.xpath("//asldkfjasdlkj").first['href']
end