Crate replace_err

source ·
Expand description

Sometimes you want to throw errors away.

This crate does exactly one thing, it adds a new method to the Result type that throws away the current error, if there is one, and replaces it with a new value. You can see it in action here:

use replace_err::ReplaceErr as _;

let result = Err(1);
let result: Result<(), _> = result.replace_err("hello");
assert_eq!(result.unwrap_err(), "hello");

This is exactly equivalent to calling Result::map_err with a closure which ignores the input and returns something else. In fact, that’s how replace_err is implemented.

Most of the time, you do not want to do this. Usually you want to wrap prior errors with new layers to add context, giving you a chain of increasingly-specific and low-level explanations which error reporters can present to the user, or based on which higher-level code can take action.

However, there are some cases where you really don’t need the underlying error, and replace_err provides a convenient way to express that need.

Traits

  • Extend Result with a replace_err method.