2015-02-23 40 views
2

我正嘗試使用gem'roo'上傳文件。當我檢查類型的文件,我有這樣一個實例方法:如何在Rails應用程序中引發錯誤?

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 

有沒有辦法讓用戶看到的只是信息,並得到再次嘗試,實際上並沒有提高語法錯誤捕獲此異常?

+0

這是在控制器中嗎? – Jon 2015-02-23 14:09:19

+0

什麼?這種方法?不,它在模型中。 – ivanacorovic 2015-02-23 14:17:16

回答

0

你可以有catch塊

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

您也可以定義事務內部begin rescue

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

只有當沒有出現錯誤方法將被保存到數據庫

還要檢查Rails errors

+0

對於這個特定的代碼看起來如何?既然我會在病例陳述中獲得救援? – ivanacorovic 2015-02-23 14:35:43

+0

你把你的方法放在'begin'裏面,你可以調用'open_spreadsheet'。把'open_spreadsheet'放在'begin'塊內 – Nermin 2015-02-23 14:37:21

+0

並且我保持提升線嗎? – ivanacorovic 2015-02-23 14:40:46