Sha256: d271a182f683f1fe59e1bdb1e956474243a331742c43b25feb7b2a1ac0334a2e

Contents?: true

Size: 1.71 KB

Versions: 1

Compression:

Stored size: 1.71 KB

Contents

module ExceptionNotifier
  class SlackNotifier
    include ExceptionNotifier::BacktraceCleaner

    attr_accessor :notifier

    def initialize(options)
      begin
        @ignore_data_if = options[:ignore_data_if]

        webhook_url = options.fetch(:webhook_url)
        @message_opts = options.fetch(:additional_parameters, {})
        @notifier = Slack::Notifier.new webhook_url, options
      rescue
        @notifier = nil
      end
    end

    def call(exception, options={})
      env = options[:env] || {}
      title = "#{env['REQUEST_METHOD']} <#{env['REQUEST_URI']}>"
      data = (env['exception_notifier.exception_data'] || {}).merge(options[:data] || {})
      text = "*An exception occurred while doing*: `#{title}`\n"

      clean_message = exception.message.gsub("`", "'")
      fields = [ { title: 'Exception', value: clean_message} ]

      if exception.backtrace
        formatted_backtrace = "```#{exception.backtrace.first(5).join("\n")}```"
        fields.push({ title: 'Backtrace', value: formatted_backtrace })
      end

      unless data.empty?
        deep_reject(data, @ignore_data_if) if @ignore_data_if.is_a?(Proc)
        data_string = data.map{|k,v| "#{k}: #{v}"}.join("\n")
        fields.push({ title: 'Data', value: "```#{data_string}```" })
      end

      attchs = [color: 'danger', text: text, fields: fields, mrkdwn_in: %w(text fields)]

      @notifier.ping '', @message_opts.merge(attachments: attchs) if valid?
    end

    protected

    def valid?
      !@notifier.nil?
    end

    def deep_reject(hash, block)
      hash.each do |k, v|
        if v.is_a?(Hash)
          deep_reject(v, block)
        end

        if block.call(k, v)
          hash.delete(k)
        end
      end
    end

  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
exception_notification-4.1.2 lib/exception_notifier/slack_notifier.rb