Search code examples
rubyruby-on-rails-6newrelicsentry

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


Want to log an error that I can use with a Sentry/New Relic, etc. when an error is raised, but I rescue it. Currently I use Sentry and it emails me all raised errors so I can fix them. However, when I rescue the error, no error gets raised, hence no idea anything is wrong.

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

Solution

  • Assuming that you have the sentry-raven gem setup, you can also call

    Raven.capture_exception(e)
    

    For your example that should be

    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
    

    to ensure that the issue is still reported to sentry.

    If your goal is to just report any text, the answer would be

    Raven.capture_message("your text")
    

    Also see: https://docs.sentry.io/platforms/ruby/usage/#reporting-messages