Example_cel_CommonErrors showcases handling common runtime errors (division by zero, index out of bounds, missing key) as documented in https://celbyexample.com/common-errors/
()
| 23 | // Example_cel_CommonErrors showcases handling common runtime errors (division by zero, index out of bounds, missing key) |
| 24 | // as documented in https://celbyexample.com/common-errors/ |
| 25 | func Example_cel_CommonErrors() { |
| 26 | vars := map[string]any{ |
| 27 | "m": map[string]int64{"a": 1}, |
| 28 | "l": []int64{10, 20}, |
| 29 | } |
| 30 | |
| 31 | exprs := []string{ |
| 32 | `1 / 0`, |
| 33 | `l[5]`, |
| 34 | `m["missing"]`, |
| 35 | } |
| 36 | |
| 37 | for _, expr := range exprs { |
| 38 | prg, err := cel.Compile(expr, |
| 39 | cel.Variable("m", cel.MapType(cel.StringType, cel.IntType)), |
| 40 | cel.Variable("l", cel.ListType(cel.IntType)), |
| 41 | ) |
| 42 | if err != nil { |
| 43 | fmt.Printf("%s -> compile error: %v\n", expr, err) |
| 44 | continue |
| 45 | } |
| 46 | _, _, err = prg.Eval(vars) |
| 47 | if err != nil { |
| 48 | fmt.Printf("%s -> runtime error: %v\n", expr, err) |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | // Output: |
| 53 | // 1 / 0 -> runtime error: division by zero |
| 54 | // l[5] -> runtime error: index out of bounds: 5 |
| 55 | // m["missing"] -> runtime error: no such key: missing |
| 56 | } |
| 57 | |
| 58 | // Example_cel_NameResolution showcases scope resolution order and macro variable shadowing |
| 59 | // as documented in https://celbyexample.com/name-resolution/ |