add error handling to deferred execution

This commit is contained in:
John Bintz 2012-09-15 12:26:55 -04:00
parent f8ebf9fbb1
commit 1c2744a3aa
3 changed files with 25 additions and 8 deletions

View File

@ -27,16 +27,20 @@ def call(env)
end end
``` ```
Nothing to configure, just drop it in to your Rack middleware stack and Only one thing to configure, the error handler if something explodes during the deferred
use Thin as your server: callback (since you no longer have your Rack handlers at that point):
``` ruby ``` ruby
# for Rails: # for Rails:
config.middleware.insert_before(::Rack::Lock, ::Rack::EMStream) config.middleware.insert_before(::Rack::Lock, ::Rack::EMStream) do |exception, environment|
# do something when there's a deferred error
end
# for Rack::Builder and derivatives: # for Rack::Builder and derivatives:
use Rack::EMStream use Rack::EMStream do |exception, environment|
# do something when there's a deferred error
end
``` ```

View File

@ -4,8 +4,8 @@ module Rack
class EMStream class EMStream
include EventMachine::Deferrable include EventMachine::Deferrable
def initialize(app) def initialize(app, &block)
@app = app @app, @block = app, block
end end
def each(&b) def each(&b)
@ -22,7 +22,20 @@ module Rack
EM.next_tick { EM.next_tick {
env['async.callback'].call [ result[0], result[1], self ] env['async.callback'].call [ result[0], result[1], self ]
result[2].each { |data| EM.next_tick { @callback.call(data) } } begin
result[2].each { |data|
EM.next_tick {
begin
@callback.call(data)
rescue => e
@callback.call(@block.call(e, env)) if @block
end
}
}
rescue => e
@callback.call(@block.call(e, env)) if @block
end
EM.next_tick { succeed } EM.next_tick { succeed }
} }

View File

@ -1,5 +1,5 @@
module Rack module Rack
class EMStream class EMStream
VERSION = "0.1.0" VERSION = "0.1.1"
end end
end end