Problems with catching an exception

Hi all

I'm having some basic newbie problem with catching an exception.
The following code does not seem to catch the URI::InvalidURIError,
because the line record.errors.add... is never executed.

  def validates_url_form_of(*attr_names)
    attr_name = attr_names.first.to_s

    validates_each(attr_name) do |record, attr_name, value|
      uri = URI.parse(record.send(attr_name.to_sym))
      if uri.class != URI::HTTP
        record.errors.add(attr_name, 'Only HTTP protocol addresses can
be used')
      end
    end
  rescue URI::InvalidURIError
    errors.add(attr_name, 'The format of the url is not valid.')
  end

I tried it the following way:

  def validates_url_form_of(*attr_names)
    attr_name = attr_names.first.to_s

    validates_each(attr_name) do |record, attr_name, value|
      uri = URI.parse(record.send(attr_name.to_sym))
      if uri.class != URI::HTTP
        record.errors.add(attr_name, 'Only HTTP protocol addresses can
be used')
      end
      rescue URI::InvalidURIError
        errors.add(attr_name, 'The format of the url is not valid.')
      end
    end
  end

But this gives me a syntax error.

What am I missing?

Thanks a lot.
Josh

···

--
Posted via http://www.ruby-forum.com/.

"rescue" clauses should be either part of a def ... end construct like this

  def my_method
  ...
  rescue URI::InvalidURIError
  end

or -- and it is your case here -- in a begin ... end construct like this

  begin
  <code which raises>
  rescue URI::InvalidURIError
  end

···

--
Sylvain Joyeux

Thank you. :slight_smile:

···

--
Posted via http://www.ruby-forum.com/.