Skip to content

Commit

Permalink
feat: Instantiate exception classes and set missing backtrace in reject.
Browse files Browse the repository at this point in the history
  • Loading branch information
dylanahsmith committed Feb 11, 2016
1 parent bf61af5 commit 837376c
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 4 deletions.
2 changes: 1 addition & 1 deletion config/flog.yml
@@ -1,2 +1,2 @@
---
threshold: 9.7
threshold: 10.6
2 changes: 1 addition & 1 deletion config/reek.yml
Expand Up @@ -60,7 +60,7 @@ TooManyInstanceVariables:
TooManyMethods:
enabled: true
exclude: []
max_methods: 12
max_methods: 13
TooManyStatements:
enabled: true
exclude:
Expand Down
12 changes: 11 additions & 1 deletion lib/promise.rb
Expand Up @@ -63,7 +63,7 @@ def fulfill(value = nil)
def reject(reason = nil)
dispatch do
@state = :rejected
@reason = reason || Error.new.tap { |err| err.set_backtrace(caller) }
@reason = reason_coercion(reason || Error)
end
end

Expand All @@ -73,6 +73,16 @@ def defer

private

def reason_coercion(reason)
case reason
when Exception
reason.set_backtrace(caller) unless reason.backtrace
when Class
reason = reason_coercion(reason.new) if reason <= Exception
end
reason
end

def add_callback(&generator)
if pending?
@callbacks << generator
Expand Down
23 changes: 22 additions & 1 deletion spec/unit/promise_spec.rb
Expand Up @@ -8,8 +8,9 @@
let(:value) { double('value') }
let(:other_value) { double('other_value') }

let(:backtrace) { caller }
let(:reason) do
StandardError.new('reason').tap { |err| err.set_backtrace(caller) }
StandardError.new('reason').tap { |err| err.set_backtrace(backtrace) }
end
let(:other_reason) do
StandardError.new('other_reason').tap { |err| err.set_backtrace(caller) }
Expand Down Expand Up @@ -400,6 +401,26 @@
expect(subject.reason.backtrace.join)
.to include(__FILE__ + ':' + (__LINE__ - 2).to_s)
end

it 'leaves backtrace if already set' do
subject.reject(reason)
expect(subject.reason.backtrace).to eq(backtrace)
end

it 'instantiates exception class' do
subject.reject(Exception)
expect(subject.reason).to be_a(Exception)
end

it 'instantiates exception subclasses' do
subject.reject(RuntimeError)
expect(subject.reason).to be_a(RuntimeError)
end

it "doesn't instantiate non-error classes" do
subject.reject(Hash)
expect(subject.reason).to eq(Hash)
end
end

describe '#sync' do
Expand Down

0 comments on commit 837376c

Please sign in to comment.