diff options
author | Azul <azul@riseup.net> | 2016-09-20 09:14:43 +0200 |
---|---|---|
committer | Azul <azul@riseup.net> | 2016-09-21 12:48:06 +0200 |
commit | dd71240fe4f4f968b9b687917cb6d7ad5812ba48 (patch) | |
tree | da0e5718dddba4f435e0ab8f7c596c438ffab403 /lib | |
parent | a1c7d68b05f142322a190b450971d27c076310a9 (diff) |
rescue and track exceptions in handler chain
Diffstat (limited to 'lib')
-rw-r--r-- | lib/nickserver/handler_chain.rb | 28 |
1 files changed, 25 insertions, 3 deletions
diff --git a/lib/nickserver/handler_chain.rb b/lib/nickserver/handler_chain.rb index a0eba4d..afc24a5 100644 --- a/lib/nickserver/handler_chain.rb +++ b/lib/nickserver/handler_chain.rb @@ -5,8 +5,11 @@ # will call the handlers with the given args until one of them returns a result # that is truethy (i.e. not false or nil). # -# Extracted from the dispatcher so we can also handle exceptions here in the -# future. +# You can specify exception classes to rescue with +# handler_chain.continue_on ErrorClass1, ErrorClass2 +# These exceptions will be rescued and tracked. The chain will proceed even if +# one handler raised the given exception. Afterwards you can inspect them with +# handler_chain.rescued_exceptions # module Nickserver @@ -14,13 +17,32 @@ module Nickserver def initialize(*handlers) @handlers = handlers + @exceptions_to_rescue = [] + @rescued_exceptions = [] + end + + def continue_on(*exceptions) + self.exceptions_to_rescue += exceptions end def handle(*args) result = nil - _handled_by = @handlers.find{|h| result = h.call(*args)} + _handled_by = @handlers.find{|h| result = try_handler(h, *args)} result end + attr_reader :rescued_exceptions + + protected + + attr_writer :rescued_exceptions + attr_accessor :exceptions_to_rescue + + def try_handler(handler, *args) + result = handler.call(*args) + rescue *exceptions_to_rescue + self.rescued_exceptions << $! + result = false + end end end |