Forum: Ruby How to access response code with mechanize

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Todd A. Jacobs (Guest)
on 2007-06-13 10:05
(Received via mailing list)
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 P. (Guest)
on 2007-06-13 10:28
(Received via mailing list)
On Wed, Jun 13, 2007 at 03:03:58PM +0900, Todd A. Jacobs wrote:
> 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!
Luis P. (Guest)
on 2007-06-13 21:14
(Received via mailing list)
On 6/13/07, Aaron P. <removed_email_address@domain.invalid> wrote:
> > This doesn't quite do what I need. What I really want is to display the
>     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
This topic is locked and can not be replied to.