How to catch error exception in ActionMailer

前端 未结 5 823
误落风尘
误落风尘 2020-12-05 00:58

The problem is how can I catch exception in delivering mail by ActionMailer. For me it sounds impossible, because in this case ActionMailer should sent mail to mailserver, a

5条回答
  •  悲哀的现实
    2020-12-05 01:21

    If you are sending a lot of emails, you can also keep your code more DRY and get notifications of exceptions to your email by doing something like this:

    status = Utility.try_delivering_email do
      ClientMailer.signup_confirmation(@client).deliver
    end
    
    unless status
      flash.now[:error] = "Something went wrong when we tried sending you and email :("
    end
    

    Utility Class:

    class Utility
      # Logs and emails exception
      # Optional args:
      # request: request Used for the ExceptionNotifier
      # info: "A descriptive messsage"
      def self.log_exception(e, args = {})
        extra_info = args[:info]
    
        Rails.logger.error extra_info if extra_info
        Rails.logger.error e.message
        st = e.backtrace.join("\n")
        Rails.logger.error st
    
        extra_info ||= ""
        request = args[:request]
        env = request ? request.env : {}
        ExceptionNotifier::Notifier.exception_notification(env, e, :data => {:message => "Exception: #{extra_info}"}).deliver
      end
    
      def self.try_delivering_email(options = {}, &block)
        begin
          yield
          return true
        rescue  EOFError,
                IOError,
                TimeoutError,
                Errno::ECONNRESET,
                Errno::ECONNABORTED,
                Errno::EPIPE,
                Errno::ETIMEDOUT,
                Net::SMTPAuthenticationError,
                Net::SMTPServerBusy,
                Net::SMTPSyntaxError,
                Net::SMTPUnknownError,
                OpenSSL::SSL::SSLError => e
          log_exception(e, options)
          return false
        end
      end
    end
    

    Got my original inspiration from here: http://www.railsonmaui.com/blog/2013/05/08/strategies-for-rails-logging-and-error-handling/

提交回复
热议问题