Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to return a Custom Error from inside a closure | Rust

I have a closure that looks like this:

pub fn getBytes(bytes: Vec<String>) -> Result(String, InputError) {
    bytes.iter().for_each(|byte| {
        let mut fixed_byte = String::new();
        if byte.contains("0x") {
            fixed_byte = dict::add_push(byte);
            if fixed_byte.trim() == String::from("Wrong length") {
                return Err(InputError::WrongHexLength(byte.to_string())); // Problem is here
            }
        }
        bytecode.push_str(&fixed_byte);
    });
    Ok(bytecode)
}

And I want to return a custom error, but since it’s inside a closure I get an error like this:

mismatched types
   --> src/lib.rs:110:24
    |
110 |                 return Err(InputError::WrongHexLength(byte.to_string()))
;
    |                        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 expected `()`, found enum `Result`
    |
    = note: expected unit type `()`
                    found enum `Result<_, InputError>`

How can I terminate what the closure does and just return the error?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks!

>Solution :

Use try_for_each. As documentation says:

An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error.

Alternatively use for loop and more imperative approach instead of functional for_each.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading