Skip to content
GitLab
Menu
Why GitLab
Pricing
Contact Sales
Explore
Why GitLab
Pricing
Contact Sales
Explore
Sign in
Get free trial
Changes
Page history
Update rust error
authored
Jun 02, 2021
by
umaumax
Show whitespace changes
Inline
Side-by-side
rust/rust-error.md
View page @
9470d3cd
[[
_TOC_
]]
## error handling
概念としては,
[
Nicer error reporting \- Command Line Applications in Rust
](
https://rust-cli.github.io/book/tutorial/errors.html
)
のページがわかりやすいが,
__注意点として,`failure`はメンテナンスされていない([From failure to Fehler]( https://boats.gitlab.io/blog/post/failure-to-fehler/ ))__
とりあえず,下記のいずれかを使ってみる(どちらを使ったほうが良いかは,各ページ下部の
`Comparison to XXX`
に説明がある)
*
[
anyhow \- crates\.io: Rust Package Registry
](
https://crates.io/crates/anyhow
)
*
独自のエラー型にこだわらない場合(簡単に利用できるので,おすすめ)
*
[
thiserror \- crates\.io: Rust Package Registry
](
https://crates.io/crates/thiserror
)
*
独自のエラー型にこだわる場合
独自のエラー型の実装としては,下記のページが参考になる
[
std::error::Error \- Rust
](
https://doc.rust-lang.org/std/error/trait.Error.html#examples
)
独自のエラー型を外部ライブラリを利用しないで定義する場合
e.g.
`Box::new(XXXError{ message: name.to_string() }))`
```
rust
use
std
::{
fmt
,
error
};
#[derive(Debug)]
struct
XXXError
{
message
:
String
,
}
impl
error
::
Error
for
XXXError
{}
impl
fmt
::
Display
for
XXXError
{
fn
fmt
(
&
self
,
f
:
&
mut
fmt
::
Formatter
<
'_
>
)
->
fmt
::
Result
{
write!
(
f
,
"XXXError occurred!: {}"
,
self
.message
)
}
}
```
`struct XXXError(String);`
としてしまうと,再帰的に
`fmt`
を呼び出してしまうのでNG
`thiserror`
を利用した場合との比較はこちら
[
Rustの便利クレート \- Qiita
](
https://qiita.com/qryxip/items/7c16ab9ef3072c1d7199#thiserror
)
`anyhow`
の使い方は
[
Refactor: use error handling lib 'anyhow' · umaumax/rust\-examples@37540cc
](
https://github.com/umaumax/rust-examples/commit/37540ccf1422833371fd01171467a4eda4577d21
)
を参照
`one-off`
(一回限り)のエラーに関しては
`anyhow!`
を利用すると良い
[
anyhow::bail \- Rust
](
https://docs.rs/anyhow/1.0.38/anyhow/macro.bail.html
)
って何?
そのときは,下記の記述が必要
```
rust
#[macro_use]
extern
crate
anyhow
;
```
ライブラリを利用しない場合は
[
Rustのエラーとなかよくなる \- 3c1uのブログ
](
https://3c1u.hatenablog.com/entry/2019/09/18/060000
)
のページがわかりやすい
まとめとしては,
[
Best error\-handling practices \- Jan 2020 : rust
](
https://www.reddit.com/r/rust/comments/ej67aa/best_errorhandling_practices_jan_2020/
)
の意見に賛同
サーベイはこちら
[
Error Handling Survey
](
https://blog.yoshuawuyts.com/error-handling-survey/
)
### thiserror
```
rust
...
...
...
...