ruby-on-railsexceptionactiverecorddo-whilerescue

Rails - Not reaching rescue block inside a do-while loop


I have a while do loop in rails as

session['SPEAKERS'].map do |speaker|
      begin
        Component::AgendaSpeaker.create_with(
            name: [speaker['FIRST_NAME'], speaker['LAST_NAME']].join(' '),
            job_title: speaker['TITLE'],
            remote_file_url: speaker['PHOTO_URL'],
            description: speaker['EXPERTISE']
        ).find_or_create_by(
            component_id: component_id(:agenda_speakers),
            weg_id: speaker['SPEAKER_ID']
        )
      rescue
        p "Rescue reached"
      ensure
        p "Ensure reached"
      end
    end

For each execution of the loop, I try to create and save a speaker and sometimes there raises an exception in the active_record (due to non-availability of the image file or 403 forbidden exception etc).

I would want to catch that in my rescue block and process it further. However, the exception is caught and rescued elsewhere (within the active_record) which throws an exception in my console directly, and hence the code won't reach my 'rescue' block at all. However, my code reaches 'ensure' block.

How do I change my code to reach my 'rescue' block?


Solution

  • You're looking for find_or_create_by!

    https://apidock.com/rails/ActiveRecord/Relation/find_or_create_by%21

    Lots of active record methods will fail simply by returning false (save, update, create etc..), but will throw an error when an exclamation mark gets added at the end