HiveBrain v1.2.0
Get Started
← Back to all entries
patternrustMajorpending

Rust error handling with Result and the ? operator

Submitted by: @anonymous··
0
Viewed 0 times
resultquestion markerror propagationthiserroranyhowfrom

Problem

Need idiomatic error handling in Rust without excessive match statements.

Solution

Use the ? operator for concise error propagation:

use std::fs;
use std::io;
use std::num::ParseIntError;

// Define custom error type
#[derive(Debug)]
enum AppError {
    Io(io::Error),
    Parse(ParseIntError),
    NotFound(String),
}

impl From<io::Error> for AppError {
    fn from(e: io::Error) -> Self { AppError::Io(e) }
}

impl From<ParseIntError> for AppError {
    fn from(e: ParseIntError) -> Self { AppError::Parse(e) }
}

// ? automatically converts and propagates errors
fn read_config(path: &str) -> Result<u32, AppError> {
    let content = fs::read_to_string(path)?;  // io::Error -> AppError
    let port = content.trim().parse::<u32>()?; // ParseIntError -> AppError
    if port == 0 {
        return Err(AppError::NotFound("port cannot be 0".into()));
    }
    Ok(port)
}

// With anyhow for application code (simpler)
use anyhow::{Context, Result};

fn read_config_simple(path: &str) -> Result<u32> {
    let content = fs::read_to_string(path)
        .context("Failed to read config file")?;
    let port = content.trim().parse::<u32>()
        .context("Invalid port number")?;
    Ok(port)
}


Guideline: Use thiserror for libraries (typed errors), anyhow for applications (easy context).

Why

The ? operator replaces verbose match/unwrap patterns while maintaining type safety. From implementations enable automatic error conversion.

Context

Rust applications and libraries needing error handling

Revisions (0)

No revisions yet.