Boxed Errors Travel Across Threads

Box errors as dyn Error + Send + Sync so failures from worker threads carry context and still move across thread boundaries.

RustResilience

Code

rustsnippet
42 lines
use std::error::Error;
use std::fmt;
use std::thread;

#[derive(Debug)]
struct ParseError {
    line: usize,
    text: String,
}

impl fmt::Display for ParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "bad record at line {}: {:?}", self.line, self.text)
    }
}

impl Error for ParseError {}

// 线程边界要求 'static + Send:错误要能从 worker 传回主线程
fn parse_one(line: usize, raw: &str) -> Result<u32, Box<dyn Error + Send + Sync>> {
    raw.parse::<u32>().map_err(|_| {
        Box::new(ParseError { line, text: raw.to_string() })
            as Box<dyn Error + Send + Sync>
    })
}

fn main() {
    let rows = vec!["120", "x4", "300"];
    let mut total = 0u32;
    for (index, raw) in rows.iter().enumerate() {
        match parse_one(index + 1, raw) {
            Ok(value) => total += value,
            Err(err) => println!("skip: {err}"),
        }
    }
    println!("total: {total}");

    // 同一类型可以直接跨线程传递:Send + Sync 是编译期保证
    let err = parse_one(9, "bad").unwrap_err();
    let handle = thread::spawn(move || err.to_string());
    println!("from worker: {}", handle.join().unwrap());
}

Inside the snippet

One way to read it: the functions fmt, parse_one and main, doing all the work.

One loop does the cycling here: for (index, raw) in rows.iter().enumerate(). Fallible operations return Result, forcing the caller to handle both arms explicitly. A match enumerates the value’s possible shapes, and the compiler rejects any arm you forget.

Watch out for

  • It runs on toolchain defaults alone, with no extras required.
  • Errors travel through Result; if you drop the ? operators while adapting, each call site needs its own match.

Using it

Key surface, verbatim: fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result

The demo output is labeled (skip:, total:, from worker:), so the run narrates itself line by line.

Start the program and main runs parse_one one after another.

Key statements

fn parse_one(line: usize, raw: &str) -> Result<u32, Box<dyn Error + Send + Sync>> {
    raw.parse::<u32>().map_err(|_| {
        Box::new(ParseError { line, text: raw.to_string() })
            as Box<dyn Error + Send + Sync>
    })
}
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    write!(f, "bad record at line {}: {:?}", self.line, self.text)
}
let handle = thread::spawn(move || err.to_string());

Interactive Tools for This Topic

FAQ

Is there exception handling?
No panics — `Result` values carry the failure.
What does Boxed Errors Travel Across Threads print when run?
Running the file directly is enough — expect labeled output lines such as `skip:`, `total:`, `from worker:`.