From fd73ff713f4f90011b6f7337ae5a6115597f5a4d Mon Sep 17 00:00:00 2001 From: Mark Spanbroek Date: Thu, 15 Apr 2021 09:41:32 +0200 Subject: [PATCH] Adds `failure` overload that uses `result` to determine type --- Readme.md | 8 ++++---- questionable/results.nim | 6 ++++++ testmodules/result/test.nim | 11 +++++++++-- 3 files changed, 19 insertions(+), 6 deletions(-) diff --git a/Readme.md b/Readme.md index f67bed2..adc5580 100644 --- a/Readme.md +++ b/Readme.md @@ -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 diff --git a/questionable/results.nim b/questionable/results.nim index 3ad1655..fc7dfa0 100644 --- a/questionable/results.nim +++ b/questionable/results.nim @@ -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 diff --git a/testmodules/result/test.nim b/testmodules/result/test.nim index 7f4b84c..5fdf56a 100644 --- a/testmodules/result/test.nim +++ b/testmodules/result/test.nim @@ -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():