Nicer error reporting - Command Line Applications in Rust
Nicer error reporting - Command Line Applications in Rust
Nicer error reporting - Command Line Applications in Rust
いろいろあるエラー出力
code:rs
let result = match std::fs::read_to_string("test.txt"){
Ok(content) => { content },
Err(error) => { panic!("{}", error); }
};
||
let result = std::fs::read_to_string("test.txt").unwrap();
Rustでエラーを戻り値にして処理
Rustでエラーを戻り値にして処理
Result Errを掴んだ場合に、式の最後に?を追加しておくと
Errの内容を戻り値として出力。
関数の型を-> Result<T, Box<dyn std::error::Error>> という戻り値に。
Tは正常系における戻り値型
dyn std::error::ErrorはErrorトレイトを継承する全ての型
Boxは動的なデータを格納するための型?
Box in std::boxed - Rust
?をつけると、異常系のときに、Errを関数の戻り値として返すところまで自動でやってくれる
code:rs
let result = std::fs::read_to_string("test.txt");
let content = match result {
Ok(content) => { content },
Err(error) => { return Err(error.into()); }
};
||
let result = std::fs::read_to_string("test.txt")?;
Providing Context
anyhowクレートを使うと、発生したエラーオブジェクトとともに、標準エラーへ詳細を報告できる
エラーメッセージへの文字列埋め込みも可能に。
より細かなエラー報告が可能に。
こんな感じ
anyhowのResult<Output>は、Result<Output, anyhow::Error>と等しい。
code:how_to_anyhow.rs
fn open_url(url:&str) -> Result<Output>{
let value = Command::new("open")
.arg(url)
.output()
.with_context(|| format!("could not open {}", url))?;
Ok(value)
}
// これはエラーになる。
// 正常系のとき、帰ってくるのがOutputであって、Result<Output>型でないため。
fn open_url(url:&str) -> Result<Output>{
Command::new("open")
.arg(url)
.output()
.with_context(|| format!("could not open {}", url))?;
}
code:stderr
Error: could not read file test.txt
Caused by:
No such file or directory (os error 2)
#WebScrap #Bookmark