# How to use Rails' exception handling mechanism in a background thread?

**URL:** <https://www.ruby-forum.com/t/how-to-use-rails-exception-handling-mechanism-in-a-background-thread/150498>\
**Category:** Rails\
**Created:** [October 9, 2008, 6:45am UTC](https://www.ruby-forum.com/t/how-to-use-rails-exception-handling-mechanism-in-a-background-thread/150498 "2008-10-09T06:45:08Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Myron\_M](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/f17d59/32.png) [@Myron\_M](https://www.ruby-forum.com/u/Myron_M)\
**Post date:** [October 9, 2008, 6:45am UTC](https://www.ruby-forum.com/t/how-to-use-rails-exception-handling-mechanism-in-a-background-thread/150498/1 "2008-10-09T06:45:08Z")

</div>

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
