mirror of
https://github.com/google/comprehensive-rust.git
synced 2025-05-16 23:55:42 +02:00
No need for thiserror as well as anyhow.
This commit is contained in:
parent
9fa0e89e90
commit
e5c97e12cb
@ -7,14 +7,7 @@ custom error types:
|
|||||||
```rust,editable,compile_fail
|
```rust,editable,compile_fail
|
||||||
use std::{fs, io};
|
use std::{fs, io};
|
||||||
use std::io::Read;
|
use std::io::Read;
|
||||||
use thiserror::Error;
|
use anyhow::{Context, Result, bail};
|
||||||
use anyhow::{Context, Result};
|
|
||||||
|
|
||||||
#[derive(Error, Debug)]
|
|
||||||
enum ReadUsernameError {
|
|
||||||
#[error("Found no username in {0}")]
|
|
||||||
EmptyUsername(String),
|
|
||||||
}
|
|
||||||
|
|
||||||
fn read_username(path: &str) -> Result<String> {
|
fn read_username(path: &str) -> Result<String> {
|
||||||
let mut username = String::with_capacity(100);
|
let mut username = String::with_capacity(100);
|
||||||
@ -23,7 +16,7 @@ fn read_username(path: &str) -> Result<String> {
|
|||||||
.read_to_string(&mut username)
|
.read_to_string(&mut username)
|
||||||
.context("Failed to read")?;
|
.context("Failed to read")?;
|
||||||
if username.is_empty() {
|
if username.is_empty() {
|
||||||
return Err(ReadUsernameError::EmptyUsername(String::from(path)).into());
|
bail!("Found no username in {path}");
|
||||||
}
|
}
|
||||||
Ok(username)
|
Ok(username)
|
||||||
}
|
}
|
||||||
@ -39,7 +32,8 @@ fn main() {
|
|||||||
|
|
||||||
<details>
|
<details>
|
||||||
|
|
||||||
* `anyhow::Result<T>` is generic and it can hold any `Error` implementation without changing the type signature.
|
* `anyhow::Result<V>` is a type alias for `Result<V, anyhow::Error>`.
|
||||||
|
* `anyhow::Error` is generic and it can hold any `Error` implementation without changing the type signature.
|
||||||
* Actual error type inside of it can be extracted for examination if necessary.
|
* Actual error type inside of it can be extracted for examination if necessary.
|
||||||
* Functionality provided by `anyhow::Result<T>` may be familiar to Go developers, as it provides similar usage patterns and ergonomics
|
* Functionality provided by `anyhow::Result<T>` may be familiar to Go developers, as it provides similar usage patterns and ergonomics
|
||||||
of `(T, error)` from Go.
|
of `(T, error)` from Go.
|
||||||
|
Loading…
x
Reference in New Issue
Block a user