【问题标题】:Ruby rescue multiple specific errorsRuby 拯救多个特定错误
【发布时间】:2013-11-27 06:08:47
【问题描述】:

在 Rails 中,我试图验证通过 excel 文档导入的日期。它不会通过 ActiveRecord,因此我无法使用系统中用于验证其他日期的Timeliness gem

所以我编写了自己的 gem 来验证日期的格式,但是有些日期通过了无效的日期,例如 31/04/2013,如果日期格式不正确,那么它将引发 RuntimeError我抢救并提供错误消息。但在红宝石中:

Date.new(2013,4,31)
» ArgumentError: invalid date

所以我想拯救他们中的任何一个。我只是担心会出现一些 ArgumentError 并且不会是这个确切的。所以我希望它只拯救ArgumentError: invalid date,这可能吗?

这是我写的excel日期检查器

  def as_date
    return nil if self.blank?
    begin
      date = DateDojo::DateSensei.date_format_validation(self)
      if date.class == Date
        return date
      else
        return false
      end
    rescue RuntimeError
      :invalid_date_format_to_make_validations_cry_and_die_sad_face
    rescue ArgumentError
      :dates_that_wouldnt_exist_even_in_the_correct_format
    end
  end

【问题讨论】:

  • 实际上,您的链接是指向 validates_timeliness gem,但 timeliness gem 是从中提取的,并且不依赖 ActiveRecord afaik。

标签: ruby-on-rails ruby validation date


【解决方案1】:

您可以像这样针对特定的错误消息:

begin
  ...
rescue ArgumentError => e
  if e.message =~ /invalid date/
    # Do something
  else
    puts e.message
  end
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-28
    • 1970-01-01
    • 2017-01-30
    • 1970-01-01
    • 2013-06-12
    • 2010-12-15
    • 2010-10-07
    • 2016-06-21
    相关资源
    最近更新 更多