Skip to content

Commit afae52c

Browse files
committed
Add Error handling
1 parent 2922fe3 commit afae52c

File tree

1 file changed

+45
-11
lines changed

1 file changed

+45
-11
lines changed

src/main.rs

+45-11
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,32 @@
11
use rand::Rng;
22
use serde::Serialize;
33
use std::collections::HashMap;
4-
use warp::{Filter, Rejection};
4+
use warp::{http::StatusCode, reject::Reject, Filter, Rejection, Reply};
55

66
#[derive(Debug, Serialize)]
77
struct Randnum {
88
num: i32,
99
}
1010

11+
#[derive(Debug)]
12+
enum Error {
13+
ParseError(std::num::ParseIntError),
14+
BadRange,
15+
}
16+
17+
impl Reject for Error {}
18+
19+
impl std::fmt::Display for Error {
20+
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
21+
match *self {
22+
Error::ParseError(ref err) => write!(f, "Cannot parse parameter: {}", err),
23+
Error::BadRange => write!(f, "BadRange"),
24+
}
25+
}
26+
}
27+
1128
impl Randnum {
12-
fn new(start: Option<i32>, end: Option<i32>) -> Self {
29+
fn new(start: Option<i32>, end: Option<i32>) -> Result<Self, Rejection> {
1330
let start = match start {
1431
Some(n) => n,
1532
_ => 1,
@@ -20,29 +37,45 @@ impl Randnum {
2037
_ => 1000,
2138
};
2239

40+
if start <= 0 || end <= 0 || end < start {
41+
return Err(warp::reject::custom(Error::BadRange));
42+
}
43+
2344
let random = {
2445
let mut rng = rand::thread_rng();
2546
rng.gen_range(start..=end)
2647
};
2748

28-
Self { num: random }
49+
Ok(Self { num: random })
50+
}
51+
}
52+
53+
async fn return_error(r: Rejection) -> Result<impl Reply, Rejection> {
54+
if let Some(error) = r.find::<Error>() {
55+
Ok(warp::reply::with_status(
56+
error.to_string(),
57+
StatusCode::RANGE_NOT_SATISFIABLE,
58+
))
59+
} else {
60+
Ok(warp::reply::with_status(
61+
"Route not found".to_string(),
62+
StatusCode::NOT_FOUND,
63+
))
2964
}
3065
}
3166

32-
async fn get_random(params: HashMap<String, String>) -> Result<impl warp::Reply, Rejection> {
67+
async fn get_random(params: HashMap<String, String>) -> Result<impl Reply, Rejection> {
3368
let start = match params.get("start") {
34-
Some(n) => Some(n.parse::<i32>().expect("Could not parse start")),
69+
Some(n) => Some(n.parse::<i32>().map_err(Error::ParseError)?),
3570
None => None,
3671
};
3772

3873
let end = match params.get("end") {
39-
Some(n) => Some(n.parse::<i32>().expect("Could not parse end")),
74+
Some(n) => Some(n.parse::<i32>().map_err(Error::ParseError)?),
4075
None => None,
4176
};
4277

43-
println!("start:{:?}, end:{:?}", start, end);
44-
45-
let random_number = Randnum::new(start, end);
78+
let random_number = Randnum::new(start, end)?;
4679

4780
Ok(warp::reply::json(&random_number))
4881
}
@@ -55,6 +88,7 @@ async fn main() {
5588
.and(warp::query())
5689
.and_then(get_random);
5790

58-
let route = get_random;
59-
warp::serve(route).run(([127, 0, 0, 1], 1337)).await;
91+
let routes = get_random.recover(return_error);
92+
93+
warp::serve(routes).run(([127, 0, 0, 1], 1337)).await;
6094
}

0 commit comments

Comments
 (0)