From dd71240fe4f4f968b9b687917cb6d7ad5812ba48 Mon Sep 17 00:00:00 2001 From: Azul Date: Tue, 20 Sep 2016 09:14:43 +0200 Subject: rescue and track exceptions in handler chain --- lib/nickserver/handler_chain.rb | 28 +++++++++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-) (limited to 'lib') 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 -- cgit v1.2.3