Forum: Ruby on Rails How to use Rails' exception handling mechanism in a background thread?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Myron M. (Guest)
on 2008-10-09 08:45
(Received via mailing list)
I have some simple asynchronous processing that my app needs to do,
and I wanted something a bit lighter weight than any of the gems or
plugins I've run across that handle background processing.  I decided
to roll my own, with the added benefit that I get to use native
threads rather than green threads since I'm using JRuby.

I'm unsure how to handle exceptions in the background thread. I'd like
to pass it to Rails' exception handling mechanism so that it is dealt
with in the same way as exceptions that occur during the normal
request-response cycle (except for rendering the 500 page, of
course).  Since I've got the exception notifier plugin installed, this
would email me, as well as log the exception to the log file.

Is there a way to let Rails handle the exception, where whatever
exception handling I have in my rails app would get used for
exceptions in the background thread?

In case it helps, I've included the code for my background thread
below.

Thanks,
Myron


class UserSubmissionProcessor
  SLEEP_TIME = 30 unless defined? SLEEP_TIME
  @@semaphore = Mutex.new
  @@singleton_thread = nil unless defined? @@singleton_thread

  def self.start_processor_if_necessary
    @@semaphore.synchronize do
      if @@singleton_thread.nil?
        @@singleton_thread = Thread.new
{UserSubmissionProcessor.process}
      end
    end
  end

  private

  def self.process
    while true
      begin
        user_submission = UserSubmission.find(:first, :conditions =>
{:processing_completed => nil}, :order => 'created_at')

        if user_submission
          user_submission.process
        else
          sleep SLEEP_TIME
        end
      rescue Exception => ex
        #TODO: how to I propagate exceptions to rails' exception-
handling mechanism?
      end
    end
  end
end
This topic is locked and can not be replied to.