mirror of
https://github.com/logos-storage/questionable.git
synced 2026-01-02 13:53:11 +00:00
Adds failure overload that uses result to determine type
This commit is contained in:
parent
86bfcc1a47
commit
fd73ff713f
@ -146,16 +146,16 @@ proc example: ?!int =
|
||||
# either return an integer or an error
|
||||
```
|
||||
|
||||
Assigning values is done using the `success` and `failure` procs:
|
||||
Results can be made using the `success` and `failure` procs:
|
||||
|
||||
```nim
|
||||
proc works: ?!seq[int] =
|
||||
# always returns a Result holding a sequence
|
||||
@[1, 1, 2, 2, 2].success
|
||||
success @[1, 1, 2, 2, 2]
|
||||
|
||||
proc fails: ?!seq[int] =
|
||||
# always returns a Result holding a ValueError
|
||||
seq[int].failure newException(ValueError, "something went wrong")
|
||||
# always returns a Result holding an error
|
||||
failure "something went wrong"
|
||||
```
|
||||
|
||||
### Binding, chaining, fallbacks and operators
|
||||
|
||||
@ -21,6 +21,12 @@ proc failure*(T: type, error: ref CatchableError): ?!T =
|
||||
proc failure*(T: type, message: string): ?!T =
|
||||
T.failure newException(ResultFailure, message)
|
||||
|
||||
template failure*(error: ref CatchableError): auto =
|
||||
err error
|
||||
|
||||
template failure*(message: string): auto =
|
||||
failure newException(ResultFailure, message)
|
||||
|
||||
proc isSuccess*[T](value: ?!T): bool =
|
||||
value.isOk
|
||||
|
||||
|
||||
@ -150,13 +150,20 @@ suite "result":
|
||||
check 42.success.option == 42.some
|
||||
check int.failure(error).option == int.none
|
||||
|
||||
test "failure can be used without type parameter in procs":
|
||||
proc fails: ?!int =
|
||||
failure "some error"
|
||||
|
||||
check fails().isFailure
|
||||
check fails().error.msg == "some error"
|
||||
|
||||
test "examples from readme work":
|
||||
|
||||
proc works: ?!seq[int] =
|
||||
@[1, 1, 2, 2, 2].success
|
||||
success @[1, 1, 2, 2, 2]
|
||||
|
||||
proc fails: ?!seq[int] =
|
||||
seq[int].failure newException(ValueError, "something went wrong")
|
||||
failure "something went wrong"
|
||||
|
||||
# binding:
|
||||
if x =? works():
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user