Skip to main content

12_boundary_error_handling/
12_boundary_error_handling.rs

1//! Demonstrating Result-zone APIs: malformed input returns Err, never panics.
2//!
3//! Run: cargo run --example 12_boundary_error_handling
4//!
5//! All external-input APIs in `matten` are Result-zone. This example shows
6//! the kinds of errors you can expect and how to handle them.
7
8use matten::{MattenError, Tensor};
9
10fn main() {
11    // ── shape/data mismatch ──────────────────────────────────────────────
12    match Tensor::try_new(vec![1.0, 2.0], &[3]) {
13        Err(MattenError::Shape { operation, message }) => {
14            println!("[Shape]  {operation}: {message}")
15        }
16        other => println!("{other:?}"),
17    }
18
19    // ── malformed JSON ───────────────────────────────────────────────────
20    match Tensor::from_json(r#"[[1.0,"text"]]"#) {
21        Err(MattenError::Parse { format, message }) => println!("[Parse/{format}]  {message}"),
22        other => println!("{other:?}"),
23    }
24
25    // ── ragged JSON array ────────────────────────────────────────────────
26    match Tensor::from_json("[[1.0,2.0],[3.0]]") {
27        Err(MattenError::Parse { format, message }) => println!("[Parse/{format}]  {message}"),
28        other => println!("{other:?}"),
29    }
30
31    // ── non-numeric CSV field ────────────────────────────────────────────
32    match Tensor::load_csv("examples/data/malformed_numeric.csv") {
33        Err(MattenError::Parse { format, message }) => println!("[Parse/{format}]  {message}"),
34        other => println!("{other:?}"),
35    }
36
37    // ── missing file ─────────────────────────────────────────────────────
38    match Tensor::load_json("/no/such/file.json") {
39        Err(MattenError::Io { path, source }) => println!("[Io]  {}: {source}", path.display()),
40        other => println!("{other:?}"),
41    }
42
43    // ── slice out of range ───────────────────────────────────────────────
44    let t = Tensor::new(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
45    match t.slice().index(5).all().build() {
46        Err(MattenError::Slice { message, .. }) => println!("[Slice]  {message}"),
47        other => println!("{other:?}"),
48    }
49
50    println!("All boundary errors handled gracefully — no panics.");
51}