【问题标题】:How to raise error in a rails app?如何在 Rails 应用程序中引发错误?
【发布时间】:2015-04-24 21:12:58
【问题描述】:

我正在尝试使用 gem 'roo' 上传文件。当我检查文件类型时,我在实例方法中有这个:

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

有没有办法捕获这个异常,以便用户只看到消息并再次尝试,而不会实际引发语法错误?

【问题讨论】:

  • 这是在控制器中吗?
  • 什么?这种方法?不,它在模型中。

标签: ruby-on-rails file-upload exception-handling roo-gem


【解决方案1】:

你可以有 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

【讨论】:

  • 使用这个特定的代码会是什么样子?因为我会在案例陈述的中间进行救援?
  • 你把你的方法放在begin里面,你调用open_spreadsheet。将open_spreadsheet 放入begin 块内
  • 我要保留加薪线吗?
  • 是的。当方法 open_spreadsheetbegin 块中调用时,它将执行其语法,如果没有匹配的文件类型,您希望方法抛出错误。当它抛出错误时,rescue 块会捕获它,你可以对消息做你喜欢的事情
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-02
  • 1970-01-01
  • 1970-01-01
  • 2015-12-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多