Skip to content
Update rust error authored by umaumax's avatar umaumax
......@@ -350,6 +350,31 @@ std::fs::File::open(path).with_context(|| format!("Failed to open config file: {
Err("hoge").map_err(|e| MyError::InternalError(e.to_string()))?;
```
### anyhowで`Result<(), Box<dyn std::error::Error>>`の型を返す方法
``` rust
use anyhow::Context;
None.with_context(|| format!("hoge error"))?;
```
`Result<_, anyhow::Error>``?`によって、自動的に`Result<(), Box<dyn std::error::Error>>`へ変換される模様
これよりももっと簡潔な方法がありそうなのだが...
`anyhow::bail!`では`anyhow::Result`型となってしまう
### Option to `Result<(), Box<dyn std::error::Error>>` by using anyhow
``` rust
use anyhow::Context;
option.with_context(|| format!("{} is not found", target))?
```
### Option to `thiserror::Error`
`thiserror`を利用した独自定義の`crate::Error::InternalError`へ変換する例
``` rust
option.ok_or_else(|| Error::InternalError())?
```
## panicではなくエラーを返す形式のassertで関数の引数チェックなどを行う
`anyhow::Error`を返り値とする場合には[ensure in anyhow - Rust]( https://docs.rs/anyhow/1.0.51/anyhow/macro.ensure.html )を利用すれば良い
......
......