How to access response code with mechanize

T

Todd A. Jacobs

I have a code segment which is intended to catch ResponseCodeError
exceptions from the mechanize library:

begin
# code
rescue ResponseCodeError
puts 'bad response code: ' + $!
end

This doesn't quite do what I need. What I really want is to display the
actual response code that mechanize is unhappy about, rather than just a
stack trace. According to the docs, WWW::Mechanize::ResponseCodeError
has an attribute named response_code, but I'm not sure I understand how
I access that within the exception handler.
 
A

Aaron Patterson

I have a code segment which is intended to catch ResponseCodeError
exceptions from the mechanize library:

begin
# code
rescue ResponseCodeError
puts 'bad response code: ' + $!
end

This doesn't quite do what I need. What I really want is to display the
actual response code that mechanize is unhappy about, rather than just a
stack trace. According to the docs, WWW::Mechanize::ResponseCodeError
has an attribute named response_code, but I'm not sure I understand how
I access that within the exception handler.

You need to assign the exception to a variable. For example:

begin
# do stuff
rescue WWW::Mechanize::ResponseCodeError => ex
puts ex.response_code
end

Do you normally expect a response code that Mechanize doesn't handle?
In other words are you just catching this error in order to debug your
code? If so, it may be more helpful to set the logger on your mechanize
object:

agent = WWW::Mechanize.new { |a| a.log = Logger.new('out.log') }

Hope that helps!
 
L

Luis Parravicini

You need to assign the exception to a variable. For example:

begin
# do stuff
rescue WWW::Mechanize::ResponseCodeError => ex
puts ex.response_code
end

You can also do it without assigning the exception to a variable, using $!:

begin
# do stuff
rescue WWW::Mechanize::ResponseCodeError
puts $!.response_code
end
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,261
Messages
2,571,308
Members
47,976
Latest member
AlanaKeech

Latest Threads

Top