-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlibrary.rs
More file actions
75 lines (65 loc) · 1.95 KB
/
library.rs
File metadata and controls
75 lines (65 loc) · 1.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
//! Typical error handling for libraries.
#![allow(
dead_code,
clippy::missing_docs_in_private_items,
clippy::print_stderr,
reason = "Example"
)]
use ::neuer_error::Result;
use self::library::NeuErrAttachments;
/// Library creators need to think about what information would be interesting for humans and what
/// machine information is necessary to handle errors programmatically.
///
/// When providing attachments, library authors should make use of the `provided_attachments!`
/// macro!
mod library {
use ::neuer_error::{NeuErr, Result, provided_attachments, traits::*};
/// Kinds of errors that are interesting to match on for library users.
/// If it is only interesting to humans, it can be iin the context instead.
#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
#[non_exhaustive]
pub enum ErrorKind {
NotFound,
InvalidInput,
}
/// Should the error be retried?
#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
pub enum Retryable {
No,
Yes,
}
// Provide discoverable, typed information for library users.
provided_attachments!(
kind(single: ErrorKind) -> Option<ErrorKind> { |kind| kind.copied() };
retryable(single: Retryable) -> bool {
|retryable| matches!(retryable, Some(Retryable::Yes))
};
);
/// Implement your errors while attaching machine-targeted information.
fn do_something_internal() -> Result<()> {
Err(NeuErr::new("Error occurred internally")
.attach(ErrorKind::InvalidInput)
.attach(Retryable::No)
.remove_marker())
}
/// Alose provide human-targeted context when propagating errors.
pub fn do_something() -> Result<()> {
do_something_internal().context("Operation failed")?;
Ok(())
}
}
fn main() -> Result<()> {
// Library users can use the machine context.
match library::do_something() {
Ok(()) => {}
Err(err) if err.retryable() => {
eprintln!("Retryable error");
}
Err(_) => {
eprintln!("Non-retryable error");
}
}
// Or just pass on the error.
library::do_something()?;
Ok(())
}