【问题标题】:Rescue, but still log error for Sentry/New Relic notification/logging救援,但仍为 Sentry/New Relic 通知/记录记录错误
【发布时间】:2020-10-15 18:03:22
【问题描述】:

当出现错误时,我想记录一个我可以与哨兵/新遗物等一起使用的错误,但我救了它。目前我使用 Sentry,它会通过电子邮件向我发送所有提出的错误,以便我修复它们。但是,当我挽救错误时,不会引发错误,因此不知道有什么问题。

class Contact
  include ActiveModel::Model
  attr_accessor :name, :email, :message

  validates :name, :phone, :message, presence: true
  validates :email, format: {with: /\A([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})\z/i}

  def deliver
    if valid?
      begin
        return ContactUsMailer.contact(self).deliver
      rescue StandardError
        errors.add(:base, I18n.t("messages.unprocessed"))
        # Want to log an error that I can use with a Sentry/New Relic, etc.
        # Currently I use Sentry and it emails me all raised errors to I can fix them.
        false
      end
    end

    false
  end
end

【问题讨论】:

    标签: ruby ruby-on-rails-6 newrelic sentry


    【解决方案1】:

    假设你有sentry-raven gem 设置,你也可以调用

    Raven.capture_exception(e)
    

    你的例子应该是

    class Contact
      include ActiveModel::Model
      attr_accessor :name, :email, :message
    
      validates :name, :phone, :message, presence: true
      validates :email, format: {with: /\A([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})\z/i}
    
      def deliver
        if valid?
          begin
            return ContactUsMailer.contact(self).deliver
          rescue StandardError => e
            Raven.capture_exception(e)
            errors.add(:base, I18n.t("messages.unprocessed"))
            # Want to log an error that I can use with a Sentry/New Relic, etc.
            # Currently I use Sentry and it emails me all raised errors to I can fix them.
            false
          end
        end
    
        false
      end
    end
    

    以确保问题仍然报告给哨兵。

    如果您的目标只是报告任何文本,答案应该是

    Raven.capture_message("your text")
    

    另见:https://docs.sentry.io/platforms/ruby/usage/#reporting-messages

    【讨论】:

      【解决方案2】:

      你可以直接manually log把错误发给Sentry:

      begin
        return ContactUsMailer.contact(self).deliver
      rescue StandardError => exception
        errors.add(:base, I18n.t("messages.unprocessed"))
        Raven.capture_exception(exception)
        false
      end
      

      【讨论】:

      • 有没有办法用 Raven 捕捉错误?还是只是例外?
      • 我不确定您是否理解您的问题?当您想将信息记录到 Raven 时,您不需要异常。例如,您可以只发送一个字符串或一个哈希。但是当ContractUsMailer 可能引发异常时,从该异常中拯救是避免向用户显示500 server error 的唯一方法。
      • 同意@spickermann 在这个案例中的例外情况。您的具体问题的答案是 capture_message docs.sentry.io/platforms/ruby/usage/#reporting-messages
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-10
      • 2017-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-21
      相关资源
      最近更新 更多