Search code examples
ruby-on-railsrubyrake

Don't stop rake task if raise an error


I have simple rake file. It imports data from the .xls file to the database. But some of the data is invalid. Then data is invalid rake stop excecuting script. But I wan to just skip this row and try with the next.

Part of my code:

data.each do |row|

username = row[0].slice!(0..2) + row[1].slice!(0..2) + rand(100).to_s
username.downcase
password = "pass1234"
User.create!(
    email: row[2].downcase,
    username: username,
    first_name: row[0],
    last_name: row[1],
    expiration_date: row[3],
    password: password,
    password_confirmation: password)
p 'done'

end

The error is about the validation, eg.:

rake aborted!
ActiveRecord::RecordInvalid: Validation failed: Expiration date must be after 2015-10-27

Script is stopped and valid records are not added.


Solution

  • Wrap it in a begin/rescue block.

    data.each do |row|
      begin 
        username = row[0].slice!(0..2) + row[1].slice!(0..2) + rand(100).to_s
        username.downcase
        password = "pass1234"
        User.create!(
            email: row[2].downcase,
            username: username,
            first_name: row[0],
            last_name: row[1],
            expiration_date: row[3],
            password: password,
            password_confirmation: password)
        p 'done'
      rescue => e
        # log exception or ignore it.
      end 
    end 
    

    Note that this works because the default rescue is for StandardError. Since ActiveRecord::RecordInvalid < StandardError. It will be 'catched'.

    You could rescue the specific error first if you only want to do something with those specific errors.

    (For reference also see the API: http://ruby-doc.org/core-2.2.0/Exception.html)