How to make ExceptionNotifier work with delayed_job in Rails 3?

delayed job work
exceptionnotification
delayed job locked by
delayed job sigterm
delayed_job start automatically

I'd like ExceptionNotifier to send out an email when an exception happens in a delayed job, just like for other exceptions. How can I achieve that?

I do this with Rails 3.2.6, delayed_job 3.0.3 and exception_notification 2.6.1 gem

# In config/environments/production.rb or config/initializers/delayed_job.rb

# Optional but recommended for less future surprises.
# Fail at startup if method does not exist instead of later in a background job 
[[ExceptionNotifier::Notifier, :background_exception_notification]].each do |object, method_name|
  raise NoMethodError, "undefined method `#{method_name}' for #{object.inspect}" unless object.respond_to?(method_name, true)
end

# Chain delayed job's handle_failed_job method to do exception notification
Delayed::Worker.class_eval do 
  def handle_failed_job_with_notification(job, error)
    handle_failed_job_without_notification(job, error)
    # only actually send mail in production
    if Rails.env.production?
      # rescue if ExceptionNotifier fails for some reason
      begin
        ExceptionNotifier::Notifier.background_exception_notification(error)
      rescue Exception => e
        Rails.logger.error "ExceptionNotifier failed: #{e.class.name}: #{e.message}"
        e.backtrace.each do |f|
          Rails.logger.error "  #{f}"
        end
        Rails.logger.flush
      end
    end
  end 
  alias_method_chain :handle_failed_job, :notification 
end

It's probably a good idea to load this code in all environments to catch errors after bundle update etc before they reach production. I do this by having a config/initializers/delayed_job.rb file but you could duplicate the code for each config/environments/* environment.

Another tip is to tune the delayed job config a bit as default you may get a lot of duplicate exception mails when job fails.

# In config/initializers/delayed_job_config.rb
Delayed::Worker.max_attempts = 3

Update I had some problems with the delayed_job daemon silently exiting and it turned out to be when ExceptionNotifier fails to send mail and no one rescued the exception. Now the code rescues and log them.

Delayed::Job Notification, I can't seem to get it to work on Rails 4 following an approach similar to: /how-to​-make-exceptionnotifier-work-with-delayed-job-in-rails-3. Following are the steps to integration of DJ in a Rails application Step#1 - (Add the gem to the Gemfile) delayed_job supports multiple backends for storing the job queue To use delayed_job with Active Record use gem delayed_job_active_record To use delayed_job with Mongoid use gem delayed_job_mongoid Example /Gemfile.rb gem 'delayed_job_active_record', '0.4.3' Run "bundle install" to…

Adding to @MattiasWadman answer, since exception_notification 4.0 there's a new way to handle manual notify. So instead of:

ExceptionNotifier::Notifier.background_exception_notification(error)

use

ExceptionNotifier.notify_exception(error)

Delayed Job Exception Notification Integration, May 3, 2014 Chain delayed job's handle_failed_job method to do exception notification Delayed::Worker.class_eval do def error).deliver rescue Exception => e Rails.logger.error "ExceptionNotifier failed: #{e.class.name}:  25 Rails 3.1 with Asset Pipeline, link_to :confirm message showing twice? 23 How to make ExceptionNotifier work with delayed_job in Rails 3? 16 How to do Rails migration involving Paperclip

Another way to handle exceptions (put as an initializer):

class DelayedErrorHandler < Delayed::Plugin

  callbacks do |lifecycle|

    lifecycle.around(:invoke_job) do |job, *args, &block|

      begin
        block.call(job, *args)
      rescue Exception => e

        # ...Process exception here...

        raise e
      end
    end
  end
end

Delayed::Worker.plugins << DelayedErrorHandler

Good rails exception notifier better than tests, Good rails exception notifier better than tests. Jan 11, 2015. Contents. 1 Basic installation; 2 Javascript notification and example error pages; 3 Delayed job; 4 Sidekiq config.ignore_if do |exception, options| # not Rails.env.production? Exception Notifier Plugin for Rails . The Exception Notifier plugin provides a mailer object and a default set of templates for sending email notifications when errors occur in a Rails application. The email includes information about the current request, session, and environment, and also gives a backtrace of the exception.

For exception_notification 3.0.0 change:

ExceptionNotifier::Notifier.background_exception_notification(error)

to:

ExceptionNotifier::Notifier.background_exception_notification(error).deliver

File: README, in Rails 3, we had to do a little work around to get delayed_job to work. # without delayed_job Notifier.signup(@user).deliver  = Exception Notifier Plugin for Rails The Exception Notifier plugin provides a mailer object and a default set of templates for sending email notifications when errors occur in a Rails application.

alias_method_chain no longer exists in Rails 5.

Here's the new (proper) way to do this using Ruby 2's prepend

# In config/initializers/delayed_job.rb
module CustomFailedJob
  def handle_failed_job(job, error)
    super
    ExceptionNotifier.notify_exception(error, data: {job: job})
  end
end

class Delayed::Worker
  prepend CustomFailedJob
end

500 error no problem. Get an email about it!, Rails 4, Heroku, Exception Notifier Rails out of the box will not notify you of 500 errors. heroku addons:create sendgrid:starter Tasks in Rails Nov 9, 2016; API Service in Rails Nov 9, 2016; Delayed Job in Rails Nov 9, 2016 Dec 15, 2016; mobile screen incredibly small on rails heroku Dec 3, 2016; Rails and Json in  exception notification. this readme is for the master branch and reflects the work currently existing on the master branch. if you are wishing to use a non-master branch of exception notification, please consult that branch's readme and not this one.

[B! Rails] delayed job, delayed job - How to make ExceptionNotifier work with delayed_job in Rails 3? - Stack Overflow. Twitterでシェア · Facebookでシェア  Exception Notifier Plugin for Rails. Contribute to buttercloud/exception_notification development by creating an account on GitHub.

Как заставить ExceptionNotifier работать с delayed_job в Rails 3?, Fail at startup if method does not exist instead of later in a background job [[​ExceptionNotifier::Notifier, :background_exception_notification]].each do |object,​  As of Rails 3 errors in routing, for example if you try to access a URL that has no route associated with it, are no longer handled by ApplicationController, they are dealt with by the middleware. If you want to handle them in the same way as all your other errors then we have to do a bit more work.

delayed_job: port exception notifications to rails 3 (c9a234ca , The main point is to ensure that all Rails apps will have a job infrastructure in place, even if it's in the form of an "immediate runner". We can then have framework features and other gems build on top of that, without having to worry about API differences between various job runners such as Delayed Job and Resque.

Comments
  • Interesting question, in looking I came across stackoverflow.com/questions/4104093/… and groups.google.com/group/delayed_job/browse_thread/thread/…
  • Yep, I've seen both of those but I think these solutions only work with Rails 2.
  • I'd recommend using the official exception notification gem at github.com/smartinez87/exception_notification
  • Ah ok, will update to that. I was using the rails3 gem as there seamd to be some rails 3 issues with the official version at the time.
  • +1 This approach works with Rails 3.2.6, Delayed Job 3.0.3, and Exception Notification 2.6.1. Initially I thought adding an error method using the built-in hook would be a cleaner approach, but that would have to be defined for each job class, and defining it generically for PerformableMethod didn't work due to how delegate is used.
  • I've added a , :data => {:job => job} to the method call so that I have a bit more details…
  • To get notified ONLY when last attempt failed I add: ExceptionNotifier.notify_exception(error) if job.attempts == Delayed::Worker.max_attempts in place of: ExceptionNotifier::Notifier.background_exception_notification(error)
  • will this also be processed in te background?
  • @DaniëlZwijnenburg The method is being called by delayed_job, so yes
  • I think this is cleanest solution. BTW other solutions wont work in the future, because alias_method_chain is deprecated in Rails 5
  • This is the answer which worked for me, running Rails 4.2.
  • @AlterLagos I think you misunderstand alias_method_chain.