前回の続き
今回はthiserrorクレートを使用したエラーハンドリングです。
[package]
name = "samplecli"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
clap = { version = "3.1.6", features = ["derive"] }
anyhow = { version = "1.0" }
thiserror = { version = "1.0" }
use thiserror::Error;
#[derive(Error, Debug)]
enum MyError {
#[error("failed to read string from {0}")]
ReadError(String),
#[error(transparent)]
ParseError(#[from] std::num::ParseIntError),
}
fn get_int_from_file() -> Result<i32, MyError> {
let path = "number.txt";
let num_str =
std::fs::read_to_string(path).map_err(|_| MyError::ReadError(path.into()))?;
num_str
.trim()
.parse::<i32>()
.map(|t| t * 2)
.map_err(MyError::from)
}
fn main() {
match get_int_from_file() {
Ok(x) => println!("{}", x),
Err(e) => println!("{:#}", e),
}
}