From 1c2744a3aa51c0ac673249ce6bacf88cfb1cdf80 Mon Sep 17 00:00:00 2001 From: John Bintz Date: Sat, 15 Sep 2012 12:26:55 -0400 Subject: [PATCH] add error handling to deferred execution --- README.md | 12 ++++++++---- lib/rack-emstream.rb | 19 ++++++++++++++++--- lib/rack-emstream/version.rb | 2 +- 3 files changed, 25 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index e91c6a6..132ae61 100644 --- a/README.md +++ b/README.md @@ -27,16 +27,20 @@ def call(env) end ``` -Nothing to configure, just drop it in to your Rack middleware stack and -use Thin as your server: +Only one thing to configure, the error handler if something explodes during the deferred +callback (since you no longer have your Rack handlers at that point): ``` ruby # 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: -use Rack::EMStream +use Rack::EMStream do |exception, environment| + # do something when there's a deferred error +end ``` diff --git a/lib/rack-emstream.rb b/lib/rack-emstream.rb index 101fecf..80195b6 100644 --- a/lib/rack-emstream.rb +++ b/lib/rack-emstream.rb @@ -4,8 +4,8 @@ module Rack class EMStream include EventMachine::Deferrable - def initialize(app) - @app = app + def initialize(app, &block) + @app, @block = app, block end def each(&b) @@ -22,7 +22,20 @@ module Rack EM.next_tick { 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 } } diff --git a/lib/rack-emstream/version.rb b/lib/rack-emstream/version.rb index 722ab32..3e6a9d2 100644 --- a/lib/rack-emstream/version.rb +++ b/lib/rack-emstream/version.rb @@ -1,5 +1,5 @@ module Rack class EMStream - VERSION = "0.1.0" + VERSION = "0.1.1" end end