-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcustom-error.rs
41 lines (39 loc) · 1.11 KB
/
custom-error.rs
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
/// # Custom Errors
/// ----------------
///
/// Custom Errors are custom made errors when standard library errors are not
/// enough to represent errors. We generally create custom error for new data
/// type or operation that is different than that from the std crate.
///
/// Some places where custom error can be defined are as follows:
/// - Libraries
/// - Web Servers
/// - Parsers, etc.
#[allow(dead_code)]
#[derive(Debug)]
enum HttpErrors {
NotFound,
PermissionDenied,
Unacceptable,
ServerError,
}
/// This is a mock fetch request that just returns custom NotFound Error
fn fetch(_path: &str) -> Result<String, HttpErrors> {
Err(HttpErrors::NotFound)
}
fn main() {
// Handling Http Errors
match fetch("/api/users/1/") {
Ok(response) => {
println!("response: {response}");
}
// Catches Custom Error: NotFound
Err(HttpErrors::NotFound) => {
println!("⛔ Custom Error: Resource Not Found in the database")
}
// Catches all other errors
Err(_) => {
println!("⛔ Custom Error: Other Errors")
}
};
}