Teach chk about Result
This commit is contained in:
parent
12a6cc2027
commit
8fd43269dc
|
@ -2,6 +2,9 @@ import
|
||||||
typetraits, strutils,
|
typetraits, strutils,
|
||||||
shims/macros, results
|
shims/macros, results
|
||||||
|
|
||||||
|
export
|
||||||
|
results
|
||||||
|
|
||||||
const
|
const
|
||||||
enforce_error_handling {.strdefine.}: string = "yes"
|
enforce_error_handling {.strdefine.}: string = "yes"
|
||||||
errorHandlingEnforced = parseBool(enforce_error_handling)
|
errorHandlingEnforced = parseBool(enforce_error_handling)
|
||||||
|
@ -152,7 +155,13 @@ template raising*[E, R](x: Raising[E, R]): R =
|
||||||
## by the `errors` pragma.
|
## by the `errors` pragma.
|
||||||
distinctBase(x)
|
distinctBase(x)
|
||||||
|
|
||||||
macro chk*[R, E](x: Raising[R, E], handlers: untyped): untyped =
|
template raising*[R, E](x: Result[R, E]): R =
|
||||||
|
tryGet(x)
|
||||||
|
|
||||||
|
macro chk*(x: Result, handlers): untyped =
|
||||||
|
discard
|
||||||
|
|
||||||
|
macro chk*(x: Raising, handlers: untyped): untyped =
|
||||||
## The `chk` macro can be used in 2 different ways
|
## The `chk` macro can be used in 2 different ways
|
||||||
##
|
##
|
||||||
## 1) Try to get the result of an expression. In case of any
|
## 1) Try to get the result of an expression. In case of any
|
||||||
|
|
|
@ -7,6 +7,18 @@ proc bar(x: int): int {.noerrors.} =
|
||||||
proc toString(x: int): string {.errors: (ValueError, KeyError, OSError).} =
|
proc toString(x: int): string {.errors: (ValueError, KeyError, OSError).} =
|
||||||
$x
|
$x
|
||||||
|
|
||||||
|
enum
|
||||||
|
ReadStatus = enum
|
||||||
|
FileNotFound
|
||||||
|
AccessDenied
|
||||||
|
HardwareError
|
||||||
|
|
||||||
|
proc readFromDevice(path: string): Result[seq[byte], ReadStatus] =
|
||||||
|
err AccessDenied
|
||||||
|
|
||||||
|
proc getGpsCoordinates(): Result[(float, float), cstring] =
|
||||||
|
ok (1.2, 3.4)
|
||||||
|
|
||||||
proc main =
|
proc main =
|
||||||
let
|
let
|
||||||
a = bar(10)
|
a = bar(10)
|
||||||
|
@ -16,6 +28,13 @@ proc main =
|
||||||
KeyError as err: err.msg
|
KeyError as err: err.msg
|
||||||
OSError: raise
|
OSError: raise
|
||||||
|
|
||||||
|
d = chk(readFromDevice("test"), @[1.byte, 2, 3])
|
||||||
|
|
||||||
|
e = chk readFromDevice("test"):
|
||||||
|
FileNotFound: raise newException()
|
||||||
|
HardwareError: quit 1
|
||||||
|
else: @[]
|
||||||
|
|
||||||
echo a
|
echo a
|
||||||
echo b
|
echo b
|
||||||
echo c
|
echo c
|
||||||
|
|
Loading…
Reference in New Issue