hcl/ext/tryfunc/README.md
Martin Atkins 55b607ac30 ext/tryfunc: Extension functions for error handling
The try(...) and can(...) functions are intended to make it more
convenient to work with deep data structures of unknown shape, by allowing
a caller to concisely try a complex traversal operation against a value
without having to guard against each possible failure mode individually.

These rely on the customdecode extension to get access to their argument
expressions directly, rather than only the results of evaluating those
expressions. The expressions can then be evaluated in a controlled manner
so that any resulting errors can be recognized and suppressed as
appropriate.
2019-12-17 07:51:07 -08:00

45 lines
1.4 KiB
Markdown

# "Try" and "can" functions
This Go package contains two `cty` functions intended for use in an
`hcl.EvalContext` when evaluating HCL native syntax expressions.
The first function `try` attempts to evaluate each of its argument expressions
in order until one produces a result without any errors.
```hcl
try(non_existent_variable, 2) # returns 2
```
If none of the expressions succeed, the function call fails with all of the
errors it encountered.
The second function `can` is similar except that it ignores the result of
the given expression altogether and simply returns `true` if the expression
produced a successful result or `false` if it produced errors.
Both of these are primarily intended for working with deep data structures
which might not have a dependable shape. For example, we can use `try` to
attempt to fetch a value from deep inside a data structure but produce a
default value if any step of the traversal fails:
```hcl
result = try(foo.deep[0].lots.of["traversals"], null)
```
The final result to `try` should generally be some sort of constant value that
will always evaluate successfully.
## Using these functions
Languages built on HCL can make `try` and `can` available to user code by
exporting them in the `hcl.EvalContext` used for expression evaluation:
```go
ctx := &hcl.EvalContext{
Functions: map[string]function.Function{
"try": tryfunc.TryFunc,
"can": tryfunc.CanFunc,
},
}
```