Various Approaches to Error Handling in Rust
CREATED: 2023 / 08 / 09 Wed
UPDATED: 2023 / 08 / 09 Wed
Error Handling with Result in Rust
Result is an enum that returns either Ok or Err. In Rust, this is the standard way to handle errors.
For example, there is a function called std::fs::read_to_string that returns Err if the specified path doesn’t exist, and Ok if it completes successfully.
// main.rs
fn main() {
let result = std::fs::read_to_string("test.txt");
match result {
Ok(content) => { println!("File content: {}", content); }
Err(error) => { println!("Oh noes: {}", error); }
}
}
$ rustc main.rs
$ ./main
Oh noes: No such file or directory (os error 2)
If the file path doesn’t exist, it outputs an error like this.
The error is printed, but execution continues with any code written after match.
If you want to terminate immediately on error, use panic!.
match result {
Ok(content) => { println!("File content: {}", content); }
Err(error) => { panic!("Oh noes: {}", error); }
}
$ ./main
thread 'main' panicked at 'Oh noes: No such file or directory (os error 2)', main.rs:5:23
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
In this case, any code after match will not execute.
Extracting the Result from match
You can read a file’s contents inside a match block, but usually you’ll want to use it outside. If processing inside Ok is sufficient, the above is fine — but let’s look at how to extract the value.
let result = std::fs::read_to_string("test.txt");
let content = match result {
Ok(content) => { content },
Err(error) => { panic!("Can't deal with {}, just exit here", error); }
};
println!("file content: {}", content);
This passes the content to content, and the println! below can then display it.
Of course, if there’s an Err, the program exits abnormally.
This code can also be written as follows, with the same behavior:
let content = std::fs::read_to_string("test.txt").unwrap();
println!("file content: {}", content);
Much cleaner. Use whichever you prefer.
But What if You Don’t Want to panic!
Sometimes you may want to pass the error result to subsequent processing without abnormal termination.
The following returns Err from the function containing this code:
let result = std::fs::read_to_string("test.txt");
let content = match result {
Ok(content) => { content },
Err(error) => { return Err(error.into()); }
};
When you compile this, you may get a return type error — the compiler complains about returning Err.
The fix is to change the function signature:
fn main() -> Result<(), Box<dyn std::error::Error>> {
let result = std::fs::read_to_string("test.txt");
let content = match result {
Ok(content) => { content },
Err(error) => { return Err(error.into()); }
};
println!("file content: {}", content);
Ok(())
}
By specifying Result as the return type, returning either Err or Ok is no longer a problem.
If the file content is retrieved, println! will output it. This should be fine for now.
The caller of this function can now handle the return value in whatever way they need.
By the way, Ok(()) on the last line is shorthand for return Ok(()).
Avoiding panic! with the Question Mark Operator
For more concise code, there is the question mark operator notation:
fn main() -> Result<(), Box<dyn std::error::Error>> {
let content = std::fs::read_to_string("test.txt")?;
println!("file content: {}", content);
Ok(())
}
This similarly returns Err on failure and Ok(()) on success.
Adding Context to Error Messages
Sometimes you want to add context explaining why an error occurred. When running the code above, a Not Found error is shown — but it’s not clear what exactly was not found. Being able to see the specific details of the problem would be very helpful.
In such cases, create a custom error struct:
struct CustomError(String);
Using this custom error struct as follows allows you to express error details more specifically:
fn main() -> Result<(), CustomError> {
let path = "test.txt";
let content = std::fs::read_to_string(path)
.map_err(|err| CustomError(format!("Error reading `{}`: {}", path, err)))?;
println!("file content: {}", content);
Ok(())
}
Error: CustomError("Error reading `test.txt`: No such file or directory (os error 2)")
Defining a custom error struct and printing specific error messages is apparently a common pattern. However, for CLI tool-style output, you can use a library called anyhow to make things look even nicer.
The Context trait from anyhow produces clean, readable output:
use anyhow::{Context, Result};
fn main() -> Result<()> {
let path = "test.txt";
let content = std::fs::read_to_string(path)
.with_context(|| format!("could not read file `{}`", path))?;
println!("file content: {}", content);
Ok(())
}
Error: could not read file `test.txt`
Caused by:
No such file or directory (os error 2)