Skip to content
Update rust error authored by umaumax's avatar umaumax
...@@ -101,6 +101,12 @@ pub enum MyError { ...@@ -101,6 +101,12 @@ pub enum MyError {
} }
``` ```
#### `anyhow::Error`から`thiserror`への移行方法
方針
* `anyhow::Result``Box<dyn std::error::Error>``pub type Result<T, E = MyError> = std::result::Result<T, E>;`へ置き換える
* 既存のエラー型を受け入れられる`thiserror`のエラー型を`Anyhow(#[from] anyhow::Error)`のようにして作成する
* `anyhow::bail!``anyhow::ensure!``thiserror`のエラー型で返せるように自前定義のマクロに置き換える
## anyhow::Resultの使い方 ## anyhow::Resultの使い方
### anyhow::Result<>は普通の構造体をエラーとして持つ場合は`?`を利用できる ### anyhow::Result<>は普通の構造体をエラーとして持つ場合は`?`を利用できる
...@@ -286,3 +292,13 @@ fn main() -> Result<(), std::io::Error> { ...@@ -286,3 +292,13 @@ fn main() -> Result<(), std::io::Error> {
``` rust ``` rust
box_error.map_err(|e| anyhow::anyhow!("{}", e))?; box_error.map_err(|e| anyhow::anyhow!("{}", e))?;
``` ```
### `std::error::Error` to `anyhow::Error`
``` rust
use anyhow::Context as _;
std::fs::File::open("config.yml").context("Failed to open config file")?;
std::fs::File::open(path).with_context(|| format!("Failed to open config file: {}", path))?;
```
`use anyhow::Context`によって、`std::error::Error``.context()`などが生える
\ No newline at end of file