How to access response code with mechanize

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.

···

--
"Oh, look: rocks!"
  -- Doctor Who, "Destiny of the Daleks"

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!

···

On Wed, Jun 13, 2007 at 03:03:58PM +0900, Todd A. Jacobs wrote:

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.

--
Aaron Patterson
http://tenderlovemaking.com/

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

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

···

On 6/13/07, Aaron Patterson <aaron@tenderlovemaking.com> wrote:

On Wed, Jun 13, 2007 at 03:03:58PM +0900, Todd A. Jacobs wrote:
> 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

--
Luis Parravicini
http://ktulu.com.ar/blog/