Retrieve optional error from Result

This commit is contained in:
Mark Spanbroek 2022-08-03 15:36:24 +02:00 committed by markspanbroek
parent b0666ba4f1
commit 13c7ff7671
2 changed files with 14 additions and 0 deletions

View File

@ -110,6 +110,14 @@ proc option*[T,E](value: Result[T,E]): ?T =
else: else:
T.none T.none
proc errorOption*[T, E](value: Result[T, E]): ?E =
## Returns an Option that contains the error from the Result, if it has one.
if value.isErr:
value.error.some
else:
E.none
Result.liftUnary(`-`) Result.liftUnary(`-`)
Result.liftUnary(`+`) Result.liftUnary(`+`)
Result.liftUnary(`@`) Result.liftUnary(`@`)

View File

@ -326,6 +326,12 @@ suite "result":
check 42.success.option == 42.some check 42.success.option == 42.some
check int.failure(error).option == int.none check int.failure(error).option == int.none
test "Result error can be converted to Option":
check (int.failure(error).errorOption == error.some)
check (42.success.errorOption == (ref CatchableError).none)
check (void.failure(error).errorOption == error.some)
check (success().errorOption == (ref CatchableError).none)
test "failure can be used without type parameter in procs": test "failure can be used without type parameter in procs":
proc fails: ?!int = proc fails: ?!int =
failure "some error" failure "some error"