Allow failure() to be called with string argument

This commit is contained in:
Mark Spanbroek 2021-03-16 09:45:06 +01:00
parent 21927f3c88
commit 74c5089d49
2 changed files with 10 additions and 0 deletions

View File

@ -6,6 +6,8 @@ include ./errorban
export resultsbase
type ResultFailure* = object of CatchableError
template `?!`*(T: typed): type Result[T, ref CatchableError] =
Result[T, ref CatchableError]
@ -15,6 +17,9 @@ proc success*[T](value: T): ?!T =
proc failure*(T: type, error: ref CatchableError): ?!T =
err(?!T, error)
proc failure*(T: type, message: string): ?!T =
T.failure newException(ResultFailure, message)
template `->?`*[T,U](value: ?!T, expression: U): ?!U =
if value.isErr:
U.failure(value.error)

View File

@ -82,6 +82,11 @@ suite "result":
check parseInt("42").catch == 42.success
check parseInt("foo").catch.error of ValueError
test "failure can be called with string argument":
let value = int.failure("some failure")
check value.error of ResultFailure
check value.error.msg == "some failure"
test "unary operator `-` works for results":
check -(-42.success) == 42.success
check -(int.failure(error)) == int.failure(error)