`anyhow` で始める: Rust エラー処理の実践的なガイド
Ethan Miller
Product Engineer · Leapcell

Preface
anyhow
は、Rust でのエラー処理によく使われるクレートです。シンプルかつ柔軟な方法でエラーを管理でき、特に迅速な開発やプロトタイピングに適しています。anyhow
は主に、汎用的なエラー型 anyhow::Error
を提供することでエラー処理を簡素化し、開発者がエラー情報を犠牲にすることなく、ボイラープレートを削減できるようにします。以下に、その機能、使い方、およびベストプラクティスを含む、anyhow
の詳細な紹介を示します。
Why Use anyhow
?
Rust では、エラー処理は通常 Result<T, E>
型を使用します。ここで、E
は std::error::Error
トレイトを実装するエラー型です。このアプローチは非常に柔軟ですが、複雑なプロジェクトでは、過剰なボイラープレートと反復的なエラー変換ロジックにつながる可能性があります。anyhow
は、一般的なエラー型を提供することで、このプロセスを簡素化します。
- 簡素化されたエラー型: すべての関数に特定のエラー型を定義する必要はありません。
- 自動エラー変換:
?
演算子を使用して、さまざまなエラー型をanyhow::Error
に自動的に変換します。 - 豊富なエラー情報: 詳細なエラーコンテキストを提供する、チェーンされたエラーメッセージをサポートします。
Basic Usage
anyhow
を使用するには、まず Cargo.toml
に依存関係を追加する必要があります。
[dependencies] anyhow = "1.0"
Creating and Returning Errors
anyhow::Error
は、anyhow!
マクロを使用して作成できます。
use anyhow::{anyhow, Result}; fn might_fail(succeed: bool) -> Result<()> { if succeed { Ok(()) } else { Err(anyhow!("Operation failed")) } }
この例では、might_fail
関数は Result
を返します。操作が失敗した場合、エラーメッセージを含む anyhow::Error
を返します。
Using the ?
Operator
anyhow
の重要な機能は、?
演算子との互換性です。これにより、さまざまなエラー型が anyhow::Error
に自動的に変換されます。
use std::fs::File; use anyhow::Result; fn open_file(filename: &str) -> Result<File> { let file = File::open(filename)?; Ok(file) }
この例では、File::open
がエラーを返した場合、?
演算子はそれを自動的に anyhow::Error
に変換して返します。
Adding Context Information
エラーを処理する際にコンテキストを提供すると、デバッグが大幅に容易になります。anyhow
は、これをサポートするために Context
トレイトを提供します。
use std::fs::File; use anyhow::{Context, Result}; fn open_file_with_context(filename: &str) -> Result<File> { let file = File::open(filename) .with_context(|| format!("Failed to open file: {}", filename))?; Ok(file) }
with_context
メソッドを使用すると、エラーチェーンにカスタムコンテキストを追加できます。これは、エラーが出力または記録されるときに表示されます。
Error Chains
anyhow::Error
はエラーチェーンをサポートしています。つまり、1つのエラーに別のエラーに関する情報を含めることができます。これは、複雑な問題をデバッグするのに非常に役立ちます。
use std::fs::File; use anyhow::{anyhow, Result}; fn read_file(filename: &str) -> Result<String> { let mut file = File::open(filename) .map_err(|e| anyhow!("Failed to open file: {}", e))?; let mut contents = String::new(); file.read_to_string(&mut contents) .map_err(|e| anyhow!("Failed to read file: {}", e))?; Ok(contents) }
この例では、map_err
を使用して、標準ライブラリのエラーを anyhow::Error
に変換し、追加のコンテキストを追加しています。
Comparison with Other Error Handling Crates
anyhow
は thiserror
や eyre
のようなクレートと似ていますが、それらの設計目標は異なります。
anyhow
: 主にアプリケーションレベルのエラー処理を目的としており、シンプルな API と柔軟性を提供します。thiserror
: カスタムエラー型を定義するために使用され、詳細なエラー型が必要なライブラリ開発に適しています。eyre
:anyhow
と似ていますが、より多くの拡張性とカスタマイズ機能を提供します。
Best Practices in Practice
- Rapid prototyping: 開発の初期段階、または迅速なイテレーションでは、
anyhow
を使用することで、エラー処理の複雑さを軽減できます。 - Application-level error handling: アプリケーションのほとんどのエラー処理ニーズに対して、
anyhow
は十分な機能を提供します。 - Combine with logging: ロギングライブラリ(
log
やtracing
など)と組み合わせて使用すると、エラーが発生したときに詳細な情報を記録できます。 - Convert errors at boundaries: ライブラリの境界では、
thiserror
を使用して特定のエラー型を定義し、アプリケーション層での変換にはanyhow
を使用することを検討してください。
Conclusion
anyhow
は Rust でのエラー処理のための強力なクレートであり、特にアプリケーションレベルのエラー管理に適しています。汎用的なエラー型と豊富なコンテキスト情報を提供することにより、エラー処理の複雑さを簡素化します。 anyhow
の機能を活用することで、開発効率とコードの可読性を大幅に向上させることができます。
We are Leapcell, your top choice for hosting Rust projects.
Leapcell is the Next-Gen Serverless Platform for Web Hosting, Async Tasks, and Redis:
Multi-Language Support
- Develop with Node.js, Python, Go, or Rust.
Deploy unlimited projects for free
- pay only for usage — no requests, no charges.
Unbeatable Cost Efficiency
- Pay-as-you-go with no idle charges.
- Example: $25 supports 6.94M requests at a 60ms average response time.
Streamlined Developer Experience
- Intuitive UI for effortless setup.
- Fully automated CI/CD pipelines and GitOps integration.
- Real-time metrics and logging for actionable insights.
Effortless Scalability and High Performance
- Auto-scaling to handle high concurrency with ease.
- Zero operational overhead — just focus on building.
Explore more in the Documentation!
Follow us on X: @LeapcellHQ