Created
November 11, 2014 23:23
-
-
Save mdunsmuir/b977f5c1d69d700db6c4 to your computer and use it in GitHub Desktop.
A questionable widget for collecting errors raised by ruby code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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