Adds failure overload that uses result to determine type

This commit is contained in:
Mark Spanbroek 2021-04-15 09:41:32 +02:00
parent 86bfcc1a47
commit fd73ff713f
3 changed files with 19 additions and 6 deletions

View File

@ -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

View File

@ -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

View File

@ -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():