#error #error-value #replace #throw #away #error-handling #err

replace_err

Adds a replace_err method to Result which throws away the current error and replaces it

3 releases (1 stable)

1.0.0 Jan 2, 2024
0.2.0 Apr 20, 2022
0.1.0 Apr 20, 2022

#1207 in Rust patterns

MIT/Apache

7KB

replace_err

Adds a method, replace_err to Result which throws away the current error and replaces it with a new error type, equivalent to result.map_err(|_| new_error_value).

License

This code is dual-licensed MIT and Apache 2.0. Take your pick.


lib.rs:

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.

No runtime deps