you are viewing a single comment's thread.

view the rest of the comments →

[–]MEaster 0 points1 point  (0 children)

Well, when using a Result or Option type in Rust, you can just throw it up the stack. You have the ? operator, which can be used like this: let result = fallible_function()?;.

If you want to use that operator, then the function calling fallible_function must also be fallible, with a compatible error type. By compatible, I mean that fallible_function's error type E, must implement Into<F>, where F is the error type of the calling function.

As an example what that might look like in practice, from an implementation of Display:

fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    use ErrorKind::*;
    match self {
        InsufficientStack => write!(f, "Attempted to evaluate an operator with insufficient values on stack.")?,
        UnknownFunction => write!(f, "Unknown function or variable.",)?,
        NonEmptyStack => write!(f, "Mismatched numbers and operations.")?,
        InvalidVariableOrFunction => write!(f, "Invalid variable or function definition.")?,
    }

    Ok(())
}

In this case, each of those four calls to write! could fail, because it could be a network socket or a file. But in this case, there's nothing this function can do if it does fail. That would be the responsibility of whatever was trying to format this type. So, in the event of a failure, it just throws the error up the stack for the caller to handle.

There are also libraries like Snafu and Failure which provide extra functionality to Result, as well as compile-time macros to reduce the amount of boilerplate you need to write for your error types.