gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 08:10:03 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com