Skip to content

Instantly share code, notes, and snippets.

@jbodah
Created October 20, 2014 23:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jbodah/2af052ca9604924016da to your computer and use it in GitHub Desktop.
Save jbodah/2af052ca9604924016da to your computer and use it in GitHub Desktop.
Ruby exception wrapping
# A generic error that implementations can use to wrap their exceptions with
class BaseWrapperException < StandardError
def initialize(e = nil)
super e
return self unless e.present? && e.is_a?(Exception)
# Preserve the original exception's data
set_backtrace e.backtrace
message.prepend "#{e.class}: "
end
end
@jbodah
Copy link
Author

jbodah commented Oct 20, 2014

require 'test_helper'

class BaseWrapperExceptionTest < ActiveSupport::TestCase
  should 'wrap exceptions' do
    class TestClass
      def self.some_test_method
        raise StandardError.new('you broke it!')
      end
    end

    original = assert_raises StandardError do
      TestClass.some_test_method
    end

    e = BaseWrapperException.new(original)

    # Should preserve all of the original exception's information
    assert e.message[/you broke it/], 'expected original exception message to be preserved'
    assert e.message[/StandardError/], 'expected original exception to be in message'
    assert e.backtrace.any? {|s| s[/some_test_method/]}, 'expected new exception to contain original backtrace'
  end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment