async_graphql_warp/
error.rs

1use std::{
2    error::Error,
3    fmt::{self, Display, Formatter},
4};
5
6use async_graphql::ParseRequestError;
7use warp::{
8    Reply,
9    http::{Response, StatusCode},
10    hyper::Body,
11    reject::Reject,
12};
13
14/// Bad request error.
15///
16/// It's a wrapper of `async_graphql::ParseRequestError`. It is also a `Reply` -
17/// by default it just returns a response containing the error message in plain
18/// text.
19#[derive(Debug)]
20pub struct GraphQLBadRequest(pub ParseRequestError);
21
22impl GraphQLBadRequest {
23    /// Get the appropriate status code of the error.
24    #[must_use]
25    pub fn status(&self) -> StatusCode {
26        match self.0 {
27            ParseRequestError::PayloadTooLarge => StatusCode::PAYLOAD_TOO_LARGE,
28            _ => StatusCode::BAD_REQUEST,
29        }
30    }
31}
32
33impl Display for GraphQLBadRequest {
34    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
35        self.0.fmt(f)
36    }
37}
38
39impl Error for GraphQLBadRequest {
40    fn source(&self) -> Option<&(dyn Error + 'static)> {
41        Some(&self.0)
42    }
43}
44
45impl Reject for GraphQLBadRequest {}
46
47impl Reply for GraphQLBadRequest {
48    fn into_response(self) -> Response<Body> {
49        Response::builder()
50            .status(self.status())
51            .body(Body::from(self.0.to_string()))
52            .unwrap()
53    }
54}
55
56impl From<ParseRequestError> for GraphQLBadRequest {
57    fn from(e: ParseRequestError) -> Self {
58        Self(e)
59    }
60}
61
62impl From<GraphQLBadRequest> for ParseRequestError {
63    fn from(e: GraphQLBadRequest) -> Self {
64        e.0
65    }
66}