medium.com 4 min read Original Source

Rust Error Handling Finally Clicked When I Stopped Using unwrap()

<button data-code="let content = std::fs::read_to_string("config.toml").unwrap();
let parsed = serde_json::from_str::(&content).unwrap();” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-1/2 -translate-y-1/2 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

let content = std::fs::read_to_string("config.toml").unwrap();
let parsed = serde_json::from_str::<Config>(&content).unwrap();
let content = std::fs::read_to_string("config.toml").unwrap();
let parsed = serde_json::from_str::<Config>(&content).unwrap();

It compiled and ran and when it didn’t, it printed called unwrap() on an Err value: Os { code: 2, kind: NotFound } and crashed with no context about where or why.

I knew unwrap() was wrong. I just didn’t know what to replace it with.

Why unwrap() feels fine at first

unwrap() is not always wrong. For a quick script that reads one file and exits, panicking on a missing file is acceptable. The file is missing, there is nothing to recover from, crash and print the error.

The problem starts when you use unwrap() in functions called from other functions. A panic deep in your call stack unwinds everything and leaves no trace of what the caller was trying to do. You lose context completely.

The other problem is that unwrap() is contagious. Once you use it in one place you use it everywhere because it is the path of least resistance. Then one day you have forty unwrap() calls across a codebase and no idea which ones are safe and which ones will blow up in production.

Result is not complicated

The fix is Result<T, E>. Most Rust functions that can fail return one.

Result {
std::fs::read_to_string(path)
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-1/2 -translate-y-1/2 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

fn read_config(path: &str) -> Result<String, std::io::Error> {
    std::fs::read_to_string(path)
}
fn read_config(path: &str) -> Result<String, std::io::Error> {
    std::fs::read_to_string(path)
}

Result has two variants. Ok(value) means it worked. Err(error) means it failed. That is it.

You handle it with match:

println!("Got: {}", content),
Err(e) => println!("Failed: {}", e),
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

match read_config("config.toml") {
    Ok(content) => println!("Got: {}", content),
    Err(e) => println!("Failed: {}", e),
}
match read_config("config.toml") {
    Ok(content) => println!("Got: {}", content),
    Err(e) => println!("Failed: {}", e),
}

This is verbose for everyday use, but it shows what is actually happening. The compiler forces you to decide what to do in both cases. There is no way to accidentally ignore an error.

The reason people actually use Result

Writing a match for every fallible call is not realistic. The ? operator handles it:

Result {
let content = std::fs::read_to_string(path)?;
Ok(content)
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

fn load_config(path: &str) -> Result<String, std::io::Error> {
    let content = std::fs::read_to_string(path)?;
    Ok(content)
}
fn load_config(path: &str) -> Result<String, std::io::Error> {
    let content = std::fs::read_to_string(path)?;
    Ok(content)
}

The ? does one thing: if the result is Ok, unwrap it and continue. If it is Err, return that error from the current function immediately. It is shorthand for this:

val,
Err(e) => return Err(e),
};” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

let content = match std::fs::read_to_string(path) {
    Ok(val) => val,
    Err(e) => return Err(e),
};
let content = match std::fs::read_to_string(path) {
    Ok(val) => val,
    Err(e) => return Err(e),
};

Two things worth knowing. First, ? only works in functions that return Result. If your function returns nothing, the compiler will tell you. Second, it propagates errors upward, so the caller has to deal with them. That is the whole point.

Where it breaks: multiple error types

Here is where most people hit a wall. You have a function that reads a file and parses it as JSON:

Result {
let content = std::fs::read_to_string(path)?; // io::Error
let config = serde_json::from_str(&content)?; // serde_json::Error
Ok(config)
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

fn load_config(path: &str) -> Result<Config, ???> {
    let content = std::fs::read_to_string(path)?;  // io::Error
    let config = serde_json::from_str(&content)?;   // serde_json::Error
    Ok(config)
}
fn load_config(path: &str) -> Result<Config, ???> {
    let content = std::fs::read_to_string(path)?;  // io::Error
    let config = serde_json::from_str(&content)?;   // serde_json::Error
    Ok(config)
}

What goes in the return type? io::Error and serde_json::Error are different types. The ? operator needs them to match the return type and they do not.

The quick fix: Box

Result<Config, Box> {
let content = std::fs::read_to_string(path)?;
let config = serde_json::from_str(&content)?;
Ok(config)
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

use std::error::Error;

fn load_config(path: &str) -> Result<Config, Box<dyn Error>> {
    let content = std::fs::read_to_string(path)?;
    let config = serde_json::from_str(&content)?;
    Ok(config)
}
use std::error::Error;

fn load_config(path: &str) -> Result<Config, Box<dyn Error>> {
    let content = std::fs::read_to_string(path)?;
    let config = serde_json::from_str(&content)?;
    Ok(config)
}

Box<dyn Error> accepts any error type. Both io::Error and serde_json::Error implement the Error trait, so ? converts them automatically. This works fine in application code where you are not exposing the function as a library API.

The proper fix: a custom error enum

For anything you want callers to actually handle, define your own error type:

Result {
let content = std::fs::read_to_string(path)?;
let config = serde_json::from_str(&content)?;
Ok(config)
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

use thiserror::Error;

#[derive(Debug, Error)]
enum ConfigError {
    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),
   #[error("Parse error: {0}")]
    Parse(#[from] serde_json::Error),
}

fn load_config(path: &str) -> Result<Config, ConfigError> {
    let content = std::fs::read_to_string(path)?;
    let config = serde_json::from_str(&content)?;
    Ok(config)
}
use thiserror::Error;

#[derive(Debug, Error)]
enum ConfigError {
    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),
   #[error("Parse error: {0}")]
    Parse(#[from] serde_json::Error),
}

fn load_config(path: &str) -> Result<Config, ConfigError> {
    let content = std::fs::read_to_string(path)?;
    let config = serde_json::from_str(&content)?;
    Ok(config)
}

The #[from] attribute generates the From implementation automatically, which is what makes ? work. When ? sees an io::Error it calls From<io::Error> for ConfigError and wraps it. The caller now gets a typed error they can match on and handle differently depending on whether the file was missing or the JSON was malformed.

Without thiserror you would write the Display and From implementations by hand. It is not hard but it is repetitive. thiserror is the standard tool for this.

When to use anyhow instead

thiserror is for when callers need to distinguish between error variants. anyhow is for when they just need to know something failed:

Result {
let content = std::fs::read_to_string(path)
.context("failed to read config file")?;
let config = serde_json::from_str(&content)
.context("failed to parse config")?;
Ok(config)
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>


use anyhow::Result;

fn load_config(path: &str) -> Result<Config> {
    let content = std::fs::read_to_string(path)
        .context("failed to read config file")?;
    let config = serde_json::from_str(&content)
        .context("failed to parse config")?;
    Ok(config)
}

use anyhow::Result;

fn load_config(path: &str) -> Result<Config> {
    let content = std::fs::read_to_string(path)
        .context("failed to read config file")?;
    let config = serde_json::from_str(&content)
        .context("failed to parse config")?;
    Ok(config)
}

anyhow::Result<T> is shorthand for Result<T, anyhow::Error> which accepts any error type. The .context() call adds a message that gets attached to the error chain. If this fails, the error message reads “failed to read config file: No such file or directory” instead of a raw OS error code. Much easier to debug.

The trade-off is that you cannot pattern-match on anyhow::Error to handle specific cases. For application-level code that surfaces errors to a user or a log, that is fine. For library code with multiple callers who need to react differently, use thiserror.

The thing that took me longest to accept

Most functions in a real Rust codebase return Result. Not just I/O functions. Parsing, validation, configuration, database calls. Almost everything that can fail returns Result.

In Java most code throws RuntimeException and you find out at runtime. In Python almost nothing is explicitly typed as fallible. In Rust the fallibility is in the type signature. A function returning String cannot fail. A function returning Result<String, Error> can. You know from reading the signature alone.

Once I stopped fighting Result, the code became easier to reason about. Functions that could fail said so in the type signature. Functions that could not fail did not. After a while, returning Result everywhere stopped feeling verbose and started feeling normal.

The simple rule

If the caller needs to react differently to different errors, use a typed enum with thiserror. If they just need to know something failed, use anyhow. If you are writing a quick script or prototype, unwrap() is fine until it is not.

Stop reaching for unwrap() as a reflex. The first time you replace it with ? and a proper return type and the code compiles cleanly, the rest of this starts to make sense on its own.

Published under Systems Engineering.

If you want to go deeper on how Rust categorizes errors at a fundamental level, I covered the recoverable versus unrecoverable distinction in an earlier piece:

In Rust, You Cannot Ignore an Error. The Compiler Guarantees It.
Not a Medium member? Read it here