3

I'm trying to upload a file using gem 'roo'. When I check for file of type, I have this in a instance method:

def open_spreadsheet
  case File.extname(file.original_filename)
    when ".xls" then Roo::Excel.new(file.path, file_warning: :ignore)
    when ".xlsx" then Roo::Excelx.new(file.path, file_warning: :ignore)
    when ".csv" then Roo::CSV.new(file.path, file_warning: :ignore)
    when ".ods" then Roo::LibreOffice.new(file.path,file_warning: :ignore)
    else raise "Unknown file type"
  end
end

Is there a way to catch this exception so that user sees just message and gets to try again, without actually raising syntax error?

ivanacorovic
  • 2,669
  • 4
  • 30
  • 46

1 Answers1

-1

You can have catch block

begin
  # call methods
rescue ErrorType => error_object
  # handle the error
end

You can also define transaction inside begin rescue block

begin
   ActiveRecord::Base.transaction do
     # call methods
   end
rescue ErrorType => error_object
  # handle the error
end

Only if no error occurs methods will be persisted to db

Also check Rails errors

Nermin
  • 6,118
  • 13
  • 23
  • How would that look like with this specific code? Since I would have rescue in the middle of case statement? – ivanacorovic Feb 23 '15 at 14:35
  • You put your method inside `begin`, where you call `open_spreadsheet`. Put `open_spreadsheet` inside `begin` block – Nermin Feb 23 '15 at 14:37
  • And do I keep the raise line? – ivanacorovic Feb 23 '15 at 14:40
  • Yes. When method `open_spreadsheet` gets called from `begin` block it will perform its syntax, and if no matching file type you want method to throw the error. When it throws error `rescue` block will catch it, and you can do with the message what you like – Nermin Feb 23 '15 at 14:43