Help with Error Handling

I need help how is the best way for error handling.

Your src/lib.rs looks good to me. You maybe could improve by removing a lot of .map_err calls, like this one:

by implementing From<ParseIntError> for TErrors:

use std::num::ParseIntError;

impl From<ParseIntError> for TErrors {
    fn from(_: ParseIntError) -> Self {
        Self::ParseID
    }
}

Then you could write:

// Parse ID string into a usize
let id = id
    .trim()
    .to_string()
    .parse::<usize>()?;

saving you a line. I saw that you get the id like that often, so this could save you some typing.

I also like the anyhow crate for error handling. Maybe using anyhow::Result will be an option for you?

Other than that, your src/lib.rs looks proper to me. I mean as long as you don't call .unwrap() or .expect() and know what your dependencies are up to (i.e. do they panic?), you are pretty safe from unexpected crashes at runtime and produced a library that is safe for others to use. Error handling in Rust is easy, because you are forced to address errors when they arise. There is no "try catch" nonsense going on where you forget to handle some obscure error arising God knows where in your call stack.

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.