Skip to content

Commit

Permalink
Merge pull request rust-cli#14 from tobark/anyhow
Browse files Browse the repository at this point in the history
  • Loading branch information
killercup authored Sep 15, 2020
2 parents a5243b6 + 334c8e9 commit fc7a12d
Show file tree
Hide file tree
Showing 7 changed files with 31 additions and 35 deletions.
10 changes: 8 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ members = [
structopt = "0.2.10"
failure = "0.1.3"
exitfailure = "0.5.1"
anyhow = "1.0"
indicatif = "0.10.1"
log = "0.4.6"
env_logger = "0.6.0"
Expand Down
3 changes: 2 additions & 1 deletion src/in-depth/signals-channels.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use std::time::Duration;
use crossbeam_channel::{bounded, tick, Receiver, select};
use anyhow::Result;

fn ctrl_channel() -> Result<Receiver<()>, ctrlc::Error> {
let (sender, receiver) = bounded(100);
Expand All @@ -10,7 +11,7 @@ fn ctrl_channel() -> Result<Receiver<()>, ctrlc::Error> {
Ok(receiver)
}

fn main() -> Result<(), exitfailure::ExitFailure> {
fn main() -> Result<()> {
let ctrl_c_events = ctrl_channel()?;
let ticks = tick(Duration::from_secs(1));

Expand Down
7 changes: 3 additions & 4 deletions src/tutorial/errors-exit.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
use failure::ResultExt;
use exitfailure::ExitFailure;
use anyhow::{Context, Result};

fn main() -> Result<(), ExitFailure> {
fn main() -> Result<()> {
let path = "test.txt";
let content = std::fs::read_to_string(path)
.with_context(|_| format!("could not read file `{}`", path))?;
.with_context(|| format!("could not read file `{}`", path))?;
println!("file content: {}", content);
Ok(())
}
35 changes: 13 additions & 22 deletions src/tutorial/errors.md
Original file line number Diff line number Diff line change
Expand Up @@ -206,32 +206,21 @@ This pattern is in fact very common.
It has one problem, though:
We don't store the original error,
only its string representation.
The often used [`failure`] library has a neat solution for that:
The often used [`anyhow`] library has a neat solution for that:
Similar to our `CustomError` type,
it has a [`Context`] type
that contains a description as well as the original error.
The library also brings with it an extension trait ([`ResultExt`])
that adds [`context()`] and [`with_context()`] methods to `Result`.

[`failure`]: https://docs.rs/failure
[`Context`]: https://docs.rs/failure/0.1.7/failure/struct.Context.html
[`ResultExt`]: https://docs.rs/failure/0.1.7/failure/trait.ResultExt.html
[`context()`]: https://docs.rs/failure/0.1.7/failure/trait.ResultExt.html#tymethod.context
[`with_context()`]: https://docs.rs/failure/0.1.7/failure/trait.ResultExt.html#tymethod.with_context

To turn these wrapped error types
into something that humans will actually want to read,
we can further add the [`exitfailure`] crate,
and use its type as the return type of our `main` function.

Let's first import the crates by adding
`failure = "0.1.7"` and `exitfailure = "0.5.1"` to the `[dependencies]` section
its [`Context`] trait can be used to add a description.
Additionally, it also keeps the original error,
so we get a "chain" of error messages pointing out the root cause.

[`anyhow`]: https://docs.rs/anyhow
[`Context`]: https://docs.rs/anyhow/1.0/anyhow/trait.Context.html

Let's first import the `anyhow` crate by adding
`anyhow = "1.0"` to the `[dependencies]` section
of our `Cargo.toml` file.

The full example will then look like this:

[`exitfailure`]: https://docs.rs/exitfailure

```rust,ignore
{{#include errors-exit.rs}}
```
Expand All @@ -240,5 +229,7 @@ This will print an error:

```text
Error: could not read file `test.txt`
Info: caused by No such file or directory (os error 2)
Caused by:
No such file or directory (os error 2)
```
3 changes: 1 addition & 2 deletions src/tutorial/testing/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,7 @@ edition = "2018"

[dependencies]
structopt = "0.2.10"
failure = "0.1.3"
exitfailure = "0.5.1"
anyhow = "1.0"

[dev-dependencies]
assert_cmd = "0.10"
Expand Down
7 changes: 3 additions & 4 deletions src/tutorial/testing/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use structopt::StructOpt;
use failure::ResultExt;
use exitfailure::ExitFailure;
use anyhow::{Context, Result};

/// Search for a pattern in a file and display the lines that contain it.
#[derive(StructOpt)]
Expand All @@ -12,10 +11,10 @@ struct Cli {
path: std::path::PathBuf,
}

fn main() -> Result<(), ExitFailure> {
fn main() -> Result<()> {
let args = Cli::from_args();
let content = std::fs::read_to_string(&args.path)
.with_context(|_| format!("could not read file `{}`", args.path.display()))?;
.with_context(|| format!("could not read file `{}`", args.path.display()))?;

find_matches(&content, &args.pattern, &mut std::io::stdout());

Expand Down

0 comments on commit fc7a12d

Please sign in to comment.