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
use std::{
    error::Error,
    fmt::{self, Display, Formatter},
};

use async_graphql::ParseRequestError;
use warp::{
    http::{Response, StatusCode},
    hyper::Body,
    reject::Reject,
    Reply,
};

/// Bad request error.
///
/// It's a wrapper of `async_graphql::ParseRequestError`. It is also a `Reply` -
/// by default it just returns a response containing the error message in plain
/// text.
#[derive(Debug)]
pub struct GraphQLBadRequest(pub ParseRequestError);

impl GraphQLBadRequest {
    /// Get the appropriate status code of the error.
    #[must_use]
    pub fn status(&self) -> StatusCode {
        match self.0 {
            ParseRequestError::PayloadTooLarge => StatusCode::PAYLOAD_TOO_LARGE,
            _ => StatusCode::BAD_REQUEST,
        }
    }
}

impl Display for GraphQLBadRequest {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

impl Error for GraphQLBadRequest {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        Some(&self.0)
    }
}

impl Reject for GraphQLBadRequest {}

impl Reply for GraphQLBadRequest {
    fn into_response(self) -> Response<Body> {
        Response::builder()
            .status(self.status())
            .body(Body::from(self.0.to_string()))
            .unwrap()
    }
}

impl From<ParseRequestError> for GraphQLBadRequest {
    fn from(e: ParseRequestError) -> Self {
        Self(e)
    }
}

impl From<GraphQLBadRequest> for ParseRequestError {
    fn from(e: GraphQLBadRequest) -> Self {
        e.0
    }
}