Message-oriented (duck-typed) exceptions
I thought somebody would implement the message-oriented exception mechanism I hinted at, but nobody did so here's the obvious implementation (4 minutes wall clock time):
Usage
def foo #... raise EX[:critical, :alert_user] # if ... # ... end def bar begin foo rescue EX[:critical] puts "Releasing resources" raise end end begin bar rescue EX[:alert_user] => e puts "=" * 80 puts "Bad news:" puts e.backtrace puts "=" * 80 end # >> Releasing resources # >> ================================================================================ # >> Bad news: # >> -:30:in `foo' # >> -:36:in `bar' # >> -:44 # >> ================================================================================
Implementation
Using respond_to? to remain close to the message-oriented nature of huh everything else:
def MOException(data, *methods) # message-oriented exceptions Class.new(Exception) do class <<self; self end.class_eval do define_method(:===){|ex| methods.any?{|m| ex.respond_to?(m)}} end methods.each{|m| define_method(m){ }} # something of interest could be done in them? maybe some sort of # negotiation between the exception and the ex. handler... define_method(:data){ data } end end EX = Class.new{ def [](*meths); MOException(nil, *meths) end }.new
That's great - Brian Mitchell (2007-03-23 (Fri) 12:17:59)
That's great, though I wonder if some exceptions I tend to use, have such boring interfaces that it makes it hard to use this outside of my own library code. Maybe this is a sign that we need our exceptions to be more interesting. This has been quite thought provoking for me. I'll keep this in mind next time I build up some exceptions and see if I can't break out of this type of one-line lazyness:
class DumbException < RuntimeException; end
Thanks for the great content you share here, Brian.
mfp 2007-03-24 (Sat) 17:39:33
Yes, it also seems to me that maybe exceptions could be more intelligent, carry more information about what went wrong and somehow collaborate with the exception handler. Just a gut feeling.
Thanks for your encouragement.
Keyword(s):[blog] [ruby] [frontpage] [message] [oriented] [exception] [subpar]
References: