W
W
weare1382015-01-27 15:54:10
Ruby on Rails
weare138, 2015-01-27 15:54:10

How to make the right exception?

Hey! Guys, such a question: I use Yandex api to display a marker on the map, at the address from the form.
I wrote this method that receives json on request to Yandex, parses it into a hash and gets the coordinates

def get_coordinates
    addr = URI.encode(URI.decode(self.address))
    http = "http://geocode-maps.yandex.ru/1.x/?format=json&geocode=#{addr}"
    json = RestClient.get(http)
    parced_json = ActiveSupport::JSON.decode(json)
    parced_json["response"]["GeoObjectCollection"]["featureMember"][0]["GeoObject"]["Point"]["pos"]
  end

so that every time when rendering a page with a map, not to make a request to Yandex, I added the coordinates field to the table and write the coordinates to this field when creating an object
, the callback method in the model
before_save :set_coordinates

  def set_coordinates
    if address_changed?
      self.coordinates = get_coordinates
    end
  end

but the problem is that the user can enter a request that is not correct for Yandex, and it needs to be processed somehow,
I changed the method in this way
def get_coordinates
    begin
      addr = URI.encode(URI.decode(self.address))
      http = "http://geocode-maps.yandex.ru/1.x/?format=json&geocode=#{addr}"
      json = RestClient.get(http)
      parced_json = ActiveSupport::JSON.decode(json)
      parced_json["response"]["GeoObjectCollection"]["featureMember"][0]["GeoObject"]["Point"]["pos"]
    rescue NoMethodError
      self.errors.add(:coordinates)
    end
  end

but the error is written not in @messages={:coordinates=>["is invalid"]}>
but in the field coordinates

how to make it so that the error is sent to the right place?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Dyachuk, 2015-01-27
@weare138

def get_coordinates
    begin
      addr = URI.encode(URI.decode(self.address))
      http = "http://geocode-maps.yandex.ru/1.x/?format=json&geocode=#{addr}"
      json = RestClient.get(http)
      parced_json = ActiveSupport::JSON.decode(json)
      coordinates = parced_json["response"]["GeoObjectCollection"]["featureMember"][0]["GeoObject"]["Point"]["pos"]
    rescue NoMethodError
      coordinates = nil
      self.errors.add(:coordinates)
    end
    coordinates
  end

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question