Skip to content

Instantly share code, notes, and snippets.

@mdunsmuir
Created November 11, 2014 23:23
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 mdunsmuir/b977f5c1d69d700db6c4 to your computer and use it in GitHub Desktop.
Save mdunsmuir/b977f5c1d69d700db6c4 to your computer and use it in GitHub Desktop.
A questionable widget for collecting errors raised by ruby code
class ErrorCollector
class DontUseThisError < StandardError; end
class DontUseThis < BasicObject
def method_missing(*args)
::Kernel.raise ::ErrorCollector::DontUseThisError.new('this object is invalid')
end
end
def initialize
@errors = {}
end
def try(message)
if block_given?
begin
yield
rescue => e
@errors[message] = e
DontUseThis.new
end
end
end
include Enumerable
def each(&block)
@errors.each(&block)
end
end
require 'minitest/autorun'
require_relative 'error_collector'
describe ErrorCollector do
before do
@ec = ErrorCollector.new
end
it 'should execute code normally and return the result' do
result = @ec.try('inconceivable!') { 'phew' }
assert_equal('phew', result)
end
it 'should catch errors you enclose in a try block' do
val = @ec.try('error?') do
raise StandardError.new('woops')
end
errors = @ec.to_h
assert_equal(1, errors.length)
assert_equal('error?', errors.keys.first)
assert_instance_of(StandardError, errors.values.first)
end
it 'should return a clearly unusable object if an error occurs in a try block' do
val = @ec.try('add two numbers') do
raise 'UH OH!!!!'
2 + 2
end
assert_raises(ErrorCollector::DontUseThisError) { val + 2 }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment