1

I know that mechanize has post_connect_hooks that will be run after the page is retrieved. However if an exception happens e.g. if you request an unknown URL like "http://dsjkhbgdfb.comsfg" then it runs pre_connect_hooks but not post_connect_hooks. Is there any way to ensure post_connect_hooks (or something similar) to always be run?

agent = Mechanize.new

agent.pre_connect_hooks << lambda do |request_agent, request|
  puts "increment a counter"
end

agent.post_connect_hooks << lambda do |request_agent, uri, response, response_body|
  puts "decrement a counter"
end

agent.get("http://dsjkhbgdfb.comsfg")
#=> increment a counter
#=> SocketError: getaddrinfo: nodename nor servname provided, or not known

As you can see, the "decrement a counter" is not run, because an error occurs before.

Niels Kristian
  • 8,661
  • 11
  • 59
  • 117

1 Answers1

0

try this as it might just force it and ignore the error

try:
agent.get("http://dsjkhbgdfb.comsfg")
except socket.error:
pass # Basically, ignore the error
Onur Gokkocabas
  • 194
  • 1
  • 11