io Error Other Boxed Failures
Wrap arbitrary failure strings into a real io::Error with Error::other, then classify both custom and filesystem errors by their ErrorKind.
Code
use std::io::{Error, ErrorKind};
fn parse_port(raw: &str) -> std::io::Result<u16> {
raw.trim().parse::<u16>().map_err(|e| {
// Error::other 把任意错误装箱成 io::Error(1.74 起取代 new(ErrorKind::Other, ..))
Error::other(format!("invalid port {:?}: {}", raw, e))
})
}
fn classify(err: &Error) -> &'static str {
// boxed custom failures and real IO errors share one ErrorKind match
match err.kind() {
ErrorKind::InvalidInput => "input rejected",
ErrorKind::NotFound => "resource missing",
_ => "unclassified failure",
}
}
fn main() {
let err = parse_port("99999").unwrap_err();
println!("message: {}", err);
println!("classification: {}", classify(&err));
// 真实 IO 错误的 kind 可直接匹配:打开不存在的文件得到 NotFound
let missing = std::fs::read("definitely-missing.txt").unwrap_err();
println!("missing file kind is NotFound: {}", missing.kind() == ErrorKind::NotFound);
}What the code does
io Error Other Boxed Failures keeps everything in the functions parse_port, classify and main.
Result is the error channel: the caller receives the failure as a value instead of an exception. The match expression is exhaustive — the compiler enforces that no case is missing.
Caveats
- Nothing to add to the project before running it.
Resultis the only error channel — remove a?while adapting and that site needs an explicitmatch.
Using it
The primary signature is fn parse_port(raw: &str) -> std::io::Result<u16>
The demo output is labeled (message:, classification:, missing file kind is NotFound:), so every printed line maps back to its originating operation.
main calls 2 helpers in sequence: parse_port and classify.
Key statements
let missing = std::fs::read("definitely-missing.txt").unwrap_err();
fn parse_port(raw: &str) -> std::io::Result<u16> {
raw.trim().parse::<u16>().map_err(|e| {
// Error::other 把任意错误装箱成 io::Error(1.74 起取代 new(ErrorKind::Other, ..))
Error::other(format!("invalid port {:?}: {}", raw, e))
})
}
let err = parse_port("99999").unwrap_err();
Interactive Tools for This Topic
FAQ
- How should callers handle failures?
- No panics — `Result` values carry the failure.
- What does io Error Other Boxed Failures print when run?
- Execute the whole file; each printed line is prefixed with a label like `message:`, `classification:`, `missing file kind is NotFound:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.