Skip to content

Commit 182371d

Browse files
committed
session 8 part 2
1 parent ce18d75 commit 182371d

File tree

3 files changed

+43
-6
lines changed

3 files changed

+43
-6
lines changed

Cargo.lock

Lines changed: 9 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

errors/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,3 +6,4 @@ edition = "2021"
66
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
77

88
[dependencies]
9+
anyhow = "1.0.44"

errors/src/main.rs

Lines changed: 33 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,27 @@
1+
use anyhow::Context;
2+
use std::error::Error;
3+
use std::fmt::{Display, Formatter};
4+
15
#[derive(Debug)]
26
enum OutOfBoundsError {
37
Overflow,
48
Underflow,
59
}
610

11+
impl Display for OutOfBoundsError {
12+
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
13+
write!(f, "{:?}", self)
14+
}
15+
}
16+
17+
impl Error for OutOfBoundsError {}
18+
19+
impl From<OutOfBoundsError> for String {
20+
fn from(v: OutOfBoundsError) -> Self {
21+
format!("{:?}", v)
22+
}
23+
}
24+
725
struct Adder<'a>(&'a i8);
826

927
impl<'a> Adder<'a> {
@@ -16,11 +34,20 @@ impl<'a> Adder<'a> {
1634
}
1735
}
1836

19-
fn main() -> Result<(), ()> {
20-
match Adder(&126).add_one() {
21-
Ok(v) => {}
22-
Err(v) => return,
23-
}
24-
Adder(&-128).sub_one().unwrap();
37+
fn always_err() -> anyhow::Result<()> {
38+
// anyhow::bail!("hello, failure")
39+
Err(anyhow::anyhow!("hello too"))
40+
}
41+
42+
fn do_it() -> anyhow::Result<()> {
43+
let v = Adder(&126).add_one()?;
44+
always_err().context("additional information")?;
45+
println!("{}", v);
46+
Adder(&-128).sub_one()?;
47+
Ok(())
48+
}
49+
50+
fn main() -> anyhow::Result<()> {
51+
do_it()?;
2552
Ok(())
2653
}

0 commit comments

Comments
 (0)