Skip to content
Update rust error authored by umaumax's avatar umaumax
...@@ -167,6 +167,19 @@ fn main() -> Result<(), Box<dyn std::error::Error>> { ...@@ -167,6 +167,19 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
let custom_error = std::io::Error::new(std::io::ErrorKind::Other, "oh no!"); let custom_error = std::io::Error::new(std::io::ErrorKind::Other, "oh no!");
``` ```
## panicではなくエラーを返す形式のassertで関数の引数チェックなどを行う
[ensure in anyhow - Rust]( https://docs.rs/anyhow/1.0.51/anyhow/macro.ensure.html )を利用すれば良い
``` rust
fn user(id: i32) -> Result<(), anyhow::Error> {
anyhow::ensure!(id != 0, "id requires non-zero value");
Ok(())
}
```
* [de-vri-es/assert2-rs: assert\!() and check\!() macros for Rust, inspired by Catch2]( https://github.com/de-vri-es/assert2-rs )`check!`を使えば良さそうと思ったがこれはスコープが終了するまでpanicを遅延するものである
* [joelparkerhenderson/assure-rust-crate: Assure rust crate: macros for Rust runtime checks and error handling]( https://github.com/joelparkerhenderson/assure-rust-crate/ ): こちらはあまり利用されていない
## 1つの関数に複数の種類のエラーが入り交じる場合の返り値のResultの型はどうする? ## 1つの関数に複数の種類のエラーが入り交じる場合の返り値のResultの型はどうする?
1. `Result<(),Box<dyn std::error::Error>>` 1. `Result<(),Box<dyn std::error::Error>>`
... ...
......