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
Dec 03, 2021
by
umaumax
Show whitespace changes
Inline
Side-by-side
rust/rust-error.md
View page @
99a3b7fc
...
@@ -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