rusterror-handlingrust-cargolinter

How to fix dylint warning "return a type that includes relevant context"?


I have a function that looks as follows:

pub fn hello() -> ResultGeneric<(), ProgramError> {
  // function body...
  some_byte_array.serialize(&mut &mut some_binary_data.borrow_mut()[start..end])?;
}

I enabled a linter (Dylint) and now it complains about lines similar to this one.

warning: returning a `std::io::Result` could discard relevant context (e.g., files or paths involved)
--> src/mod.rs:50:5
|
50 | |         some_byte_array.serialize(&mut &mut some_binary_data.borrow_mut()[start..end])?;
|  |_________________________________________________________________________________________^
|
= help: return a type that includes relevant context

As I understand, the issue here is that serialize() would return Result<T, Error>, but the code expects ProgramError. But I don't understand what I am supposed to do to fix it.

Question: How to return a result with relevant context?


Solution

  • The idea behind the lint is that returning the error as-is doesn't provide that much information on what went wrong.

    std::io::Error doesn't contain that much information, for example it can contain NotFound but won't tell you which file wasn't found.

    To fix this, you'd construct a new error that contains relevant information:

    some_byte_array
        .serialize(&mut &mut some_binary_data.borrow_mut()[start..end])
        .map_err(|err| ProgramError::some_constructor("some_byte_array failed to serialize from some_binary_data", err))?;
    

    If ProgramError isn't your type, hopefully it has a way to either include another error inside it, or add information to it somehow. If it is your type, consider making a variant for this situation so that you can match it if necessary.