github.com/hashicorp/hcl/v2@v2.20.0/ext/tryfunc/README.md (about)

     1  # "Try" and "can" functions
     2  
     3  This Go package contains two `cty` functions intended for use in an
     4  `hcl.EvalContext` when evaluating HCL native syntax expressions.
     5  
     6  The first function `try` attempts to evaluate each of its argument expressions
     7  in order until one produces a result without any errors.
     8  
     9  ```hcl
    10  try(non_existent_variable, 2) # returns 2
    11  ```
    12  
    13  If none of the expressions succeed, the function call fails with all of the
    14  errors it encountered.
    15  
    16  The second function `can` is similar except that it ignores the result of
    17  the given expression altogether and simply returns `true` if the expression
    18  produced a successful result or `false` if it produced errors.
    19  
    20  Both of these are primarily intended for working with deep data structures
    21  which might not have a dependable shape. For example, we can use `try` to
    22  attempt to fetch a value from deep inside a data structure but produce a
    23  default value if any step of the traversal fails:
    24  
    25  ```hcl
    26  result = try(foo.deep[0].lots.of["traversals"], null)
    27  ```
    28  
    29  The final result to `try` should generally be some sort of constant value that
    30  will always evaluate successfully.
    31  
    32  ## Using these functions
    33  
    34  Languages built on HCL can make `try` and `can` available to user code by
    35  exporting them in the `hcl.EvalContext` used for expression evaluation:
    36  
    37  ```go
    38  ctx := &hcl.EvalContext{
    39      Functions: map[string]function.Function{
    40          "try": tryfunc.TryFunc,
    41          "can": tryfunc.CanFunc,
    42      },
    43  }
    44  ```