Debian Codegraph @

third_party/rust/warp/examples/rejections.rs

raw
1 #![deny(warnings)]
2
3 use std::convert::Infallible;
4 use std::error::Error;
5 use std::num::NonZeroU16;
6
7 use serde_derive::{Deserialize, Serialize};
8 use warp::http::StatusCode;
9 use warp::{reject, Filter, Rejection, Reply};
10
11 /// Rejections represent cases where a filter should not continue processing
12 /// the request, but a different filter *could* process it.
13 #[tokio::main]
14 async fn main() {
15 let math = warp::path!("math" / u16);
16 let div_with_header = math
17 .and(warp::get())
18 .and(div_by())
19 .map(|num: u16, denom: NonZeroU16| {
20 warp::reply::json(&Math {
21 op: format!("{} / {}", num, denom),
22 output: num / denom.get(),
23 })
24 });
25
26 let div_with_body =
27 math.and(warp::post())
28 .and(warp::body::json())
29 .map(|num: u16, body: DenomRequest| {
30 warp::reply::json(&Math {
31 op: format!("{} / {}", num, body.denom),
32 output: num / body.denom.get(),
33 })
34 });
35
36 let routes = div_with_header.or(div_with_body).recover(handle_rejection);
37
38 warp::serve(routes).run(([127, 0, 0, 1], 3030)).await;
39 }
40
41 /// Extract a denominator from a "div-by" header, or reject with DivideByZero.
42 fn div_by() -> impl Filter<Extract = (NonZeroU16,), Error = Rejection> + Copy {
43 warp::header::<u16>("div-by").and_then(|n: u16| async move {
44 if let Some(denom) = NonZeroU16::new(n) {
45 Ok(denom)
46 } else {
47 Err(reject::custom(DivideByZero))
48 }
49 })
50 }
51
52 #[derive(Deserialize)]
53 struct DenomRequest {
54 pub denom: NonZeroU16,
55 }
56
57 #[derive(Debug)]
58 struct DivideByZero;
59
60 impl reject::Reject for DivideByZero {}
61
62 // JSON replies
63
64 /// A successful math operation.
65 #[derive(Serialize)]
66 struct Math {
67 op: String,
68 output: u16,
69 }
70
71 /// An API error serializable to JSON.
72 #[derive(Serialize)]
73 struct ErrorMessage {
74 code: u16,
75 message: String,
76 }
77
78 // This function receives a `Rejection` and tries to return a custom
79 // value, otherwise simply passes the rejection along.
80 async fn handle_rejection(err: Rejection) -> Result<impl Reply, Infallible> {
81 let code;
82 let message;
83
84 if err.is_not_found() {
85 code = StatusCode::NOT_FOUND;
86 message = "NOT_FOUND";
87 } else if let Some(DivideByZero) = err.find() {
88 code = StatusCode::BAD_REQUEST;
89 message = "DIVIDE_BY_ZERO";
90 } else if let Some(e) = err.find::<warp::filters::body::BodyDeserializeError>() {
91 // This error happens if the body could not be deserialized correctly
92 // We can use the cause to analyze the error and customize the error message
93 message = match e.source() {
94 Some(cause) => {
95 if cause.to_string().contains("denom") {
96 "FIELD_ERROR: denom"
97 } else {
98 "BAD_REQUEST"
99 }
100 }
101 None => "BAD_REQUEST",
102 };
103 code = StatusCode::BAD_REQUEST;
104 } else if let Some(_) = err.find::<warp::reject::MethodNotAllowed>() {
105 // We can handle a specific error, here METHOD_NOT_ALLOWED,
106 // and render it however we want
107 code = StatusCode::METHOD_NOT_ALLOWED;
108 message = "METHOD_NOT_ALLOWED";
109 } else {
110 // We should have expected this... Just log and say its a 500
111 eprintln!("unhandled rejection: {:?}", err);
112 code = StatusCode::INTERNAL_SERVER_ERROR;
113 message = "UNHANDLED_REJECTION";
114 }
115
116 let json = warp::reply::json(&ErrorMessage {
117 code: code.as_u16(),
118 message: message.into(),
119 });
120
121 Ok(warp::reply::with_status(json, code))
122 }