ruby-on-rails - 如何在 Rails 应用程序中引发错误?

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

我正在尝试使用 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

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

最佳答案

你可以有catch block

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

您还可以在 begin rescue block 中定义事务

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

只有当没有错误发生时,方法才会持久化到数据库

同时检查 Rails errors

关于ruby-on-rails - 如何在 Rails 应用程序中引发错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28675602/

相关文章:

ruby-on-rails - ActiveRecord::StatementInvalid: PGError: ERROR: 关系 "instructions"不存在

ruby-on-rails - <%= h…%>在Rails中是什么意思?

jquery - Rails 远程表单回调 ajax :loading does not fire, 其他人做

java - 在Struts 2中引用fileUpload拦截器时出现404错误

c# - ApplicationException 或创建自定义异常?

ruby-on-rails - Heroku 托管的 RoR 站点与 CloudFlare ssl 不工作

java - 使用 Java 将 HTML 页面以及引用的图像上传到服务器

jquery - 为什么 Blueimp 的 jQuery-File-Upload 插件不触发回调?

c# - 如何在 C# 中处理多播委托(delegate)中的异常?

python-2.7 - 检查 Python 2.7 中是否正确引发异常?