救援,但仍然记录 Sentry/New 遗物 notification/logging 的错误

Rescue, but still log error for Sentry/New Relic notification/logging

想记录一个错误,当出现错误时,我可以将其与 Sentry/New Relic 等一起使用,但我挽救了它。目前我使用 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

假设您有 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

您可以 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