Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Error Handling in Rust Applications

Sponsored · Your Podcast. Everywhere. Effortlessly. Share. Educate. Inspire. Entertain. You do you. We'll handle the rest.
Avatar for taiki45 taiki45
July 24, 2024

Error Handling in Rust Applications

"Error Handling in Rust Applications" at 「Rust、何もわからない... #13」 https://estie.connpass.com/event/320751/

Avatar for taiki45

taiki45

July 24, 2024
Tweet

More Decks by taiki45

Other Decks in Technology

Transcript

  1. © 2024 Finatext Holdings Ltd. 自動化: なにかエラーが起きてもリトライとかで回復できるものなら自動で復旧できる 可視化: 「なにが原因でエラーなのか」「回避・復旧するためのアクションはなにか」をソフトウェアのユーザー に伝える。

    良いコードはエラーの内容を見ただけで回避・復旧のアクションができる。悪いコードはコードを読まないと エラーの原因や復旧手段がわからない。 エラーハンドリングで目指すところ 3
  2. © 2024 Finatext Holdings Ltd. 主にanyhow::Error struct提供するcrate。他にも便利関数やマクロが盛りだくさん anyhow::Error ≒ Box<dyn

    std::error::Error> • std::error::Errorはtrait • dyn Traitはtrait objects • 参照(e.g. Box)越しに動的に異なる値を扱う 実際はanyhow::Result経由で使う anyhow crate 5
  3. © 2024 Finatext Holdings Ltd. anyhow::Context and Option 11 anyhowがOptionに対してもContext

    traitをimplしてくれているので、Optionに対してもwith_contextが使え る。with_contextはanyhow::Resultを返すので `?` オペレーターで上流に返せる これとunwrap_or_*系を使うとunwrapを消せるのでunwrap系のlintを有効にできて平穏
  4. © 2024 Finatext Holdings Ltd. エラーメッセージのスタイル 13 A. "Failed to

    read!" B. "failed to read!" C. "Failed to read" D. "failed to read"
  5. © 2024 Finatext Holdings Ltd. エラーメッセージのスタイル 14 ✅ (D) "failed

    to read" >Error messages are typically concise lowercase sentences without trailing punctuation https://doc.rust-lang.org/std/error/trait.Error.html
  6. © 2024 Finatext Holdings Ltd. ケーススタディ: aws-lambda-runtime v0.12 upgrade 20

    `impl Future<Output = anyhow::Result<()>>` を返すいたって普通のクロージャー