How to use anyhow with ndarray when using [i] with index out of bound?

I have an application which is huge. I wanted to know the context of from where and how the error happened. So I thought of adding context to the called functions. I am not sure if below is the right approach and if not, please guide me.

Anyway, I have a function which operates on Ndarray using multiple [i] and not get(i). I am not using latter because it is too wordy and less understandability of code.

Below is my minimal snippet,

fn caller() {
   for i = 0..10000 {
       let err = format!("This is during the caller at instance {}", i);
       called(i).expect(&err);
   }
}

fn called(i: usize) -> anyhow::Result<f32> {
   let arr = ndarray::arr1(&[1,2,3]);
   let result = arr[i] + arr[i+1];
   Ok(result)
}

With this I get below panic without any information about the line or function

thread '' panicked at 'ndarray: index out of bounds', C:\Users\selva.cargo\registry\src\github.com-1ecc6299db9ec823\ndarray-0.14.0\src\arraytraits.rs:26:5

However, if I use the below function, it is working but it is too wordy,

fn modified_called(i: usize) -> anyhow::Result<f32> {
   let arr = ndarray::arr1(&[1,2,3]);
   let result = arr.get(i).ok_or(anyhow::anyhow!("index {} out of bound", i)) + arr.get(i+1).ok_or(anyhow::anyhow!("index {} out of bound", i+1));
   Ok(result)
}

Any suggestion?

You could define a macro for it?

macro_rules! idx {
    ($var:ident [ $idx:expr ]) => {{
        let i = $idx;
        $var.get(i).ok_or(anyhow::anyhow!("index {} out of bound", i))?
    }};
}

fn called(i: usize) -> anyhow::Result<f32> {
   let arr = ndarray::arr1(&[1., 2., 3.]);
   let result = idx!(arr[i]) + idx!(arr[i+1]);
   Ok(result)
}

You can enable backtraces for panics and get information about the line of your code that causes the error. Have you tried this and is this not enough?

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.