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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
#[macro_use]
pub extern crate log;
#[macro_use]
pub extern crate serde_derive;
pub use exitfailure::ExitDisplay;
pub use failure::ResultExt;
pub mod github;
pub use github as gh;
pub fn error_handler_wrapper(res: Result<Vec<String>, u16>) -> Result<Vec<String>, String> {
match res {
Ok(res) => match res.len() {
0 => Err("User has no SSH keys available".into()),
_ => Ok(res),
},
Err(err) => match err {
404 => Err("Wrong username, doesn't exists".into()),
gh::INVALID_GH_API_RESPONSE => Err("Invalid GitHub API response".into()),
gh::INVALID_GH_USERNAME => {
Err(format!(
"Invalid username. Username isn't allowed on GitHub. \
If you think this is an bug, please create a issue on at {}/issues",
env!("CARGO_PKG_REPOSITORY")
))
}
_ => Err(format!("API response code: {}", err)),
},
}
}
#[test]
fn test_error_handling() {
let all_ok_input: Result<Vec<String>, u16> = Ok(vec!["key1".to_string(), "key2".to_string()]);
let all_ok_output: Result<Vec<String>, failure::Error> =
Ok(vec!["key1".to_string(), "key2".to_string()]);
assert_eq!(
error_handler_wrapper(all_ok_input).unwrap(),
all_ok_output.unwrap()
);
let no_keys_input: Result<Vec<String>, u16> = Ok(vec![]);
assert_eq!(error_handler_wrapper(no_keys_input).is_err(), true);
let no_user_error_code: u16 = 404;
let no_user_input: Result<Vec<String>, u16> = Err(no_user_error_code);
assert_eq!(error_handler_wrapper(no_user_input).is_err(), true);
let other_error_code: u16 = 500;
let other_error_input: Result<Vec<String>, u16> = Err(other_error_code);
assert_eq!(error_handler_wrapper(other_error_input).is_err(), true);
let invalid_user_input: Result<Vec<String>, u16> = Err(gh::INVALID_GH_USERNAME);
assert_eq!(error_handler_wrapper(invalid_user_input).is_err(), true);
let invalid_user_input: Result<Vec<String>, u16> = Err(gh::INVALID_GH_API_RESPONSE);
assert_eq!(error_handler_wrapper(invalid_user_input).is_err(), true);
}