error_handling/
error_handling.rs1use cel_core::{CelType, Env, MapActivation, Value};
6
7fn main() {
8 let env = Env::with_standard_library()
9 .with_variable("x", CelType::Int)
10 .with_variable("items", CelType::list(CelType::Int));
11
12 let mut activation = MapActivation::new();
13
14 println!("=== Division by zero ===");
16 activation.insert("x", 0);
17 let ast = env.compile("10 / x").unwrap();
18 let program = env.program(&ast).unwrap();
19 let result = program.eval(&activation);
20
21 match &result {
22 Value::Error(err) => println!("Error: {}", err),
23 other => println!("Result: {}", other),
24 }
25
26 println!("\n=== Index out of bounds ===");
28 activation.insert("items", Value::list([1, 2, 3]));
29 let ast = env.compile("items[10]").unwrap();
30 let program = env.program(&ast).unwrap();
31 let result = program.eval(&activation);
32
33 match &result {
34 Value::Error(err) => println!("Error: {}", err),
35 other => println!("Result: {}", other),
36 }
37
38 println!("\n=== Key not found ===");
40 let env = Env::with_standard_library()
41 .with_variable("config", CelType::map(CelType::String, CelType::String));
42 let mut activation = MapActivation::new();
43 activation.insert("config", Value::map([("host", "localhost")]));
44
45 let ast = env.compile("config.missing_key").unwrap();
46 let program = env.program(&ast).unwrap();
47 let result = program.eval(&activation);
48
49 match &result {
50 Value::Error(err) => println!("Error: {}", err),
51 other => println!("Result: {}", other),
52 }
53
54 println!("\n=== Safe field access with has() ===");
56 let ast = env
57 .compile("has(config.missing_key) ? config.missing_key : 'default'")
58 .unwrap();
59 let program = env.program(&ast).unwrap();
60 let result = program.eval(&activation);
61 println!("Result: {}", result);
62}