liveBook · Manning

Map_err method

As explained in Refactoring to Rust

map_err is a Result operation that transforms the error value of an Err result while leaving an Ok result unchanged.

map_err transforms the error value in a Result while leaving an Ok result unchanged. It calls a supplied function only for Err, then wraps that function's return value in the new Err variant. section 2.5.5

Converting validation errors

Suppose validate_lowercase and validate_unique both return Result<(), ()>, while validate_username must return Result<(), UsernameError>. Applying map_err converts each unit error into the matching UsernameError variant; ? then returns the converted error early. The Ok path continues without calling the conversion function. section 2.5.5

fn map_err<T, E1, E2>(
  r: Result<T, E1>,
  transform: fn(E1) -> E2,
) -> Result<T, E2> {
  match r {
    Ok(x) => Ok(x),
    Err(e) => Err(transform(e)),
  }
}

The equivalent match implementation makes the operation explicit: preserve Ok(x), transform Err(e), and wrap the transformed value in Err. section 2.5.5

fn validate_username(username: &str) -> Result<(), UsernameError>
{
  validate_lowercase(username).map_err(lowercase_err)?;
  validate_unique(username).map_err(unique_err)?;

  Ok(())
}

fn lowercase_err(x: ()) -> UsernameError {
  UsernameError::NotLowercase
}

fn unique_err(x: ()) -> UsernameError {
  UsernameError::NotUnique
}

The validation example applies named conversion functions before propagating errors with ?. Closures provide a shorter equivalent form. section 2.5.5

How Refactoring to Rust covers it

How deep it goes
Defines the Err-only transformation and shows its match-equivalent implementation, stopping short of broader API details.
Examples
Uses lowercase and uniqueness validators that convert unit errors into NotLowercase and NotUnique.
What it assumes
Assumes familiarity with Result, its Ok and Err variants, and functions or closures passed as arguments.
What you can do after
Apply it via Result::map_err to convert error types without writing an explicit Ok-case match.
How it connects
Connects Result, Ok, Err, closures, custom error types, and the ? early-return operator.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Refactoring to Rust. The section links point to the parts of the book it draws on.