From: Joel VanderWerf Date: 2008-04-03T04:09:29+09:00 Subject: Re: Does Ruby support exception wrapping (exception chaining Joel VanderWerf wrote: > Brian Hartin wrote: >> Joel, >> >> This doesn't really provide the main benefit to exception wrapping >> mechanism: the ability to wrap low-level exceptions in an appropriate >> higher-level exception and yet not lose the entire stack trace, or the >> types and messages of the low-level exceptions. Exception wrapping >> (a.k.a. chaining) in Java (a good model for this feature, I think) >> makes the idea of a 'causal Exception' part of the class (via a >> 'cause' field), and the stack trace: an Exception's stack trace >> includes the causal 'chain' of Exceptions automatically. Here's an alternative, perhaps with too much magic: class ServiceNotFoundException < StandardError attr_reader :cause def initialize cause @cause = cause end DEFAULT_MESSAGE = "The service could not be contacted" def self.[](e, msg = DEFAULT_MESSAGE) e2 = new(e) raise e2, "#{msg}: #{e.message}", e.backtrace end end begin begin raise "foo" rescue Exception => e ServiceNotFoundException[e] end rescue Exception => e_outer puts e_outer p e_outer.cause puts e_outer.backtrace.join("\n ") end __END__ Output: The service could not be contacted: foo # wrapped-exceptions.rb:17 -- vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407