Skip to content

Commit

Permalink
Add error method
Browse files Browse the repository at this point in the history
  • Loading branch information
frvade committed Nov 10, 2021
1 parent b1277b3 commit edd3ee0
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 2 deletions.
11 changes: 9 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,9 +99,16 @@ Methods:
- `failure?` – returns `true` for failure result and `false` for success result
- `value!` – unwraps a result object, returns the value for success result, and throws an error for failure result
- `value_or(other_value, &block)` – returns a value for success result or `other_value` for failure result (either calls `block` in case it given)
- `or(&block)` - calls block for failure result, for success result does nothing
- `either(success_proc, failure_proc)` - for success result calls success_proc with result value in args, for failure result calls failure_proc with error in args.
- `error` – returns `nil` for success result and error object (with code and data) for failure result
- `or(&block)` – calls block for failure result, for success result does nothing
- `either(success_proc, failure_proc)` – for success result calls success_proc with result value in args, for failure result calls failure_proc with error in args.

### Error object

In case of failure you can get an error object with error code
and data from `fail!` arguments. This can be done by method `error` on
the result object and the returned object will have corresponding
methods `code` and `data`.

### Configuration

Expand Down
8 changes: 8 additions & 0 deletions lib/resol/result.rb
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,10 @@ def value_or(*)
def value!
@value
end

def error
nil
end
end

class Failure < Result
Expand Down Expand Up @@ -68,6 +72,10 @@ def value_or(other_value = nil)
def value!
raise UnwrapError, "Failure result #{@value.inspect}"
end

def error
@value
end
end

def self.Success(...)
Expand Down
2 changes: 2 additions & 0 deletions spec/result_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
it { expect(result.failure?).to be_falsey }
it { expect(result.value_or(:other_value)).to eq(:success_value) }
it { expect(result.value!).to eq(:success_value) }
it { expect(result.error).to be_nil }
it { expect { result.or { raise "Some Error" } }.not_to raise_error }

it do
Expand All @@ -25,6 +26,7 @@
it { expect(result.success?).to be_falsey }
it { expect(result.failure?).to be_truthy }
it { expect(result.value_or(:other_value)).to eq(:other_value) }
it { expect(result.error).to eq(:failure_value) }
it { expect { result.or { raise "Some Error" } }.to raise_error("Some Error") }

it do
Expand Down

0 comments on commit edd3ee0

Please sign in to comment.