Skip to content
Update rust error authored by umaumax's avatar umaumax
...@@ -101,6 +101,9 @@ pub enum MyError { ...@@ -101,6 +101,9 @@ pub enum MyError {
} }
``` ```
### thiserrorでエラーメッセージを動的にしたい
[thiserror - Rust]( https://docs.rs/thiserror/latest/thiserror/#example )
### thiserrorでよくあるクレートのエラー型の自動変換用の定義例 ### thiserrorでよくあるクレートのエラー型の自動変換用の定義例
``` rust ``` rust
pub type Result<T, E = Error> = std::result::Result<T, E>; pub type Result<T, E = Error> = std::result::Result<T, E>;
...@@ -122,6 +125,10 @@ pub enum Error { ...@@ -122,6 +125,10 @@ pub enum Error {
} }
``` ```
* `anyhow::Error`は外部クレートの型なので、直接`From`トレイトを実装できないが、`Error::Anyhow(error)`として生成することは可能
* `anyhow::bail!`などで、`ahyhow::Error`から自動変換されない理由となる
* `Err(anyhow::anyhow!("hoge"))?;`ならばOK
### `anyhow::Error`から`thiserror`への移行方法 ### `anyhow::Error`から`thiserror`への移行方法
方針 方針
* `anyhow::Result``Box<dyn std::error::Error>``pub type Result<T, E = MyError> = std::result::Result<T, E>;`へ置き換える * `anyhow::Result``Box<dyn std::error::Error>``pub type Result<T, E = MyError> = std::result::Result<T, E>;`へ置き換える
...@@ -305,6 +312,8 @@ fn main() -> Result<(), std::io::Error> { ...@@ -305,6 +312,8 @@ fn main() -> Result<(), std::io::Error> {
} }
``` ```
## `Box<dyn std::error::Error>`周りでlifetime関連のエラーが発生した場合、思い切って、`thiserror`ですべてエラーを統一した方が良い
## 型変換 ## 型変換
### `Box<dyn std::error::Error>` to `anyhow::Error` ### `Box<dyn std::error::Error>` to `anyhow::Error`
``` rust ``` rust
...@@ -321,6 +330,11 @@ std::fs::File::open(path).with_context(|| format!("Failed to open config file: { ...@@ -321,6 +330,11 @@ std::fs::File::open(path).with_context(|| format!("Failed to open config file: {
`use anyhow::Context`によって、`std::error::Error``.context()`などが生える `use anyhow::Context`によって、`std::error::Error``.context()`などが生える
### ResultのE1をE2へ
``` rust
Err("hoge").map_err(|e| MyError::InternalError(e.to_string()))?;
```
## panicではなくエラーを返す形式のassertで関数の引数チェックなどを行う ## panicではなくエラーを返す形式のassertで関数の引数チェックなどを行う
`anyhow::Error`を返り値とする場合には[ensure in anyhow - Rust]( https://docs.rs/anyhow/1.0.51/anyhow/macro.ensure.html )を利用すれば良い `anyhow::Error`を返り値とする場合には[ensure in anyhow - Rust]( https://docs.rs/anyhow/1.0.51/anyhow/macro.ensure.html )を利用すれば良い
... ...
......